CSharp.Template/YuanXuan.IM.Api/Filters/GlobalOperationLogFilter.cs

61 lines
2.5 KiB
C#

using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Text;
namespace LearningOfficer.OA.Mobile.Api.Filters
{
public class GlobalOperationLogFilter : IAsyncActionFilter
{
private readonly ILogger<GlobalOperationLogFilter> _logger;
public GlobalOperationLogFilter(ILogger<GlobalOperationLogFilter> logger )
{
_logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
//// 获取请求信息
var paramss = context.ActionDescriptor.Parameters;
var ActionName = ((ControllerActionDescriptor)context.ActionDescriptor)?.ActionName;
var Method = context.HttpContext.Request.Method;
var queryString = context.HttpContext.Request.QueryString;
var RequestUrl = context.HttpContext.Request.Host + context.HttpContext.Request.Path;
string token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
string body = "";
var request = context.HttpContext.Request;
var stream = request.Body;
if (request.ContentLength != null && request.ContentLength > 0)
{
request.EnableBuffering();
request.Body.Position = 0;//将读取指针迻到开始位置
using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
{
body = await reader.ReadToEndAsync();
}
}
_logger.LogInformation(context.HttpContext.TraceIdentifier + ": {RequestParams}", body);
await next();
}
private async Task<string> GetRequestBody(HttpRequest request)
{
request.EnableBuffering();
var body = request.Body;
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
request.Body.Position = 0; // 重置流位置
return Encoding.UTF8.GetString(buffer);
}
private async Task<string> GetResponseBody(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var body = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return body;
}
}
}