public class LogFilter : IAsyncActionFilter
{
private readonly ILogger<LogFilter> _logger;
public LogFilter(
ILogger<LogFilter> logger
)
{
_logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var contentType = "application/json";
if (!context.ModelState.IsValid)
{
context.Result = new ContentResult()
{
Content = context.ModelState.Values.SelectMany(e => e.Errors).Select(e => e.ErrorMessage).FirstOrDefault(),
StatusCode = 500,
ContentType = contentType
};
}
var apiPath = context.HttpContext.Request.Path.ToString();
var RequestType = context.HttpContext.Request.Method;
string arguments = JsonSerializer.Serialize(context.ActionArguments);
if (RequestType == "POST" || RequestType == "PUT" || RequestType == "DELETE")
{
_logger.LogInformation($"请求方式:{RequestType},接口:{apiPath},请求参数:{arguments}");
context.Result = new ContentResult()
{
Content = "成功了. ",
StatusCode = 200,
ContentType = contentType
};
}
else if (RequestType == "GET")
{
_logger.LogInformation($"请求方式:{RequestType},接口:{apiPath},请求参数:{arguments}");
}
else
{
context.Result = new ContentResult()
{
Content = "请求方式错误!",
StatusCode = 405,
ContentType = contentType
};
}
var executedContext = await next();
Console.WriteLine("Result:" + JsonSerializer.Serialize(executedContext.Result));
}
}
builder.Services.AddMvc(option =>
{
option.Filters.Add(typeof(LogFilter));
});