- 添加过滤器
using Microsoft.AspNetCore.Http.Internal; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System.IO; using System.Text; namespace MyPro.Filters { public class LogFilter : IActionFilter { ILogger _logger; public LogFilter(ILogger<LogFilter> logger) { _logger = logger; } public void OnActionExecuted(ActionExecutedContext context) { if (!(context.Result is FileStreamResult)) { var statusCode = context.HttpContext.Response.StatusCode; var result = context.Result; _logger.LogInformation($"HashCode:{context.HttpContext.Request.GetHashCode()},路由:{context.HttpContext.Request.Path},响应码{statusCode},出参{JsonConvert.SerializeObject(result)}"); } } public void OnActionExecuting(ActionExecutingContext context) { if (context.HttpContext.Request.Path != null && !context.HttpContext.Request.Path.Value.ToLower().Contains("/user/login")) { var header = context.HttpContext.Request.Headers; var query = context.HttpContext.Request.Query; var body = string.Empty; if (context.HttpContext.Request.Method.ToUpper() == "POST") { context.HttpContext.Request.EnableRewind(); context.HttpContext.Request.Body.Seek(0, 0); using (var ms = new MemoryStream()) { context.HttpContext.Request.Body.CopyTo(ms); var b = ms.ToArray(); body = Encoding.UTF8.GetString(b); } } var log = new { query, header, body }; _logger.LogInformation($"HashCode:{context.HttpContext.Request.GetHashCode()},路由:{context.HttpContext.Request.Path},入参{JsonConvert.SerializeObject(log)}"); } } } }
- 在Startup.cs中注入服务
services.AddMvc(options => { options.Filters.Add(typeof(LogFilter)); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; });