LoggingUpDbAttribute.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using YLShipBuildLandMap.Entity;
  2. using Microsoft.AspNetCore.Mvc.Filters;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using System.Security.Claims;
  9. using System.IO;
  10. using Microsoft.AspNetCore.Http;
  11. using System.Threading.Tasks;
  12. namespace YLShipBuildLandMap.Web.Filters
  13. {
  14. public class LoggingUpDbAttribute : ActionFilterAttribute
  15. {
  16. public string DescribeCode { get; set; }
  17. private YLShipBuildLandMapContext DbContext { get; set; }
  18. public LoggingUpDbAttribute(string describeCode) {
  19. //this.DbContext = dbContext;
  20. this.DescribeCode = describeCode;
  21. }
  22. public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) {
  23. try
  24. {
  25. this.DbContext = context.HttpContext.RequestServices.GetService(typeof(YLShipBuildLandMapContext)) as YLShipBuildLandMapContext;
  26. string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
  27. var roleClaim = context.HttpContext.User.FindFirst(ClaimTypes.Name);
  28. SysLog sysLog = new SysLog();
  29. context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
  30. using (var reader = new StreamReader(context.HttpContext.Request.Body, encoding: Encoding.UTF8))
  31. {
  32. var body = reader.ReadToEndAsync();
  33. // Do some processing with body…
  34. // Reset the request body stream position so the next middleware can read it
  35. body.Wait();
  36. sysLog.LogText = body.Result;
  37. context.HttpContext.Request.Body.Position = 0;
  38. }
  39. sysLog.LogId = Guid.NewGuid();
  40. sysLog.ClientIp = ip;
  41. sysLog.LogDescribe = this.DescribeCode;
  42. sysLog.LogTitle = context.HttpContext.Request.Path.HasValue ? context.HttpContext.Request.Path.Value : "";
  43. sysLog.LogTime = DateTime.Now;
  44. sysLog.LogType = 1;
  45. sysLog.LogUser = roleClaim.Value;
  46. this.DbContext.Add(sysLog);
  47. this.DbContext.SaveChanges();
  48. }
  49. catch (Exception ex)
  50. {
  51. }
  52. return base.OnResultExecutionAsync(context, next);
  53. }
  54. }
  55. }