using YLShipBuildLandMap.Entity; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Security.Claims; using System.IO; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; namespace YLShipBuildLandMap.Web.Filters { public class LoggingUpDbAttribute : ActionFilterAttribute { public string DescribeCode { get; set; } private YLShipBuildLandMapContext DbContext { get; set; } public LoggingUpDbAttribute(string describeCode) { //this.DbContext = dbContext; this.DescribeCode = describeCode; } public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { try { this.DbContext = context.HttpContext.RequestServices.GetService(typeof(YLShipBuildLandMapContext)) as YLShipBuildLandMapContext; string ip = context.HttpContext.Connection.RemoteIpAddress.ToString(); var roleClaim = context.HttpContext.User.FindFirst(ClaimTypes.Name); SysLog sysLog = new SysLog(); context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(context.HttpContext.Request.Body, encoding: Encoding.UTF8)) { var body = reader.ReadToEndAsync(); // Do some processing with body… // Reset the request body stream position so the next middleware can read it body.Wait(); sysLog.LogText = body.Result; context.HttpContext.Request.Body.Position = 0; } sysLog.LogId = Guid.NewGuid(); sysLog.ClientIp = ip; sysLog.LogDescribe = this.DescribeCode; sysLog.LogTitle = context.HttpContext.Request.Path.HasValue ? context.HttpContext.Request.Path.Value : ""; sysLog.LogTime = DateTime.Now; sysLog.LogType = 1; sysLog.LogUser = roleClaim.Value; this.DbContext.Add(sysLog); this.DbContext.SaveChanges(); } catch (Exception ex) { } return base.OnResultExecutionAsync(context, next); } } }