創建自定義的中間件來實現我們的自定義異常處理
1 、CustomExceptionMiddleware
public class CustomExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<CustomExceptionMiddleware> _logger;
public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception e)
{
await ExceptionHandlerAsync(context, e);
}
}
private async Task ExceptionHandlerAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status200OK;
_logger.LogError($"系統出現錯誤:{ex.Message}--{ex.StackTrace}");
var result = new ResultObject(500, ex.Message);
await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CustomExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionMiddleware>();
}
}
2、Configure
//全局異常日志 app.UseMiddleware<CustomExceptionMiddleware>();
第二種
.NET Core 給我們提供了一種處理全局異常的方式,只需要稍加修改,就可以使用內置且完善的的中間件。我們需要做的修改就是在 Startup 類中修改 Configure方法:
// 全局異常捕獲
app.UseExceptionHandler(errors =>
{
errors.Run(async context =>
{
var feature = context.Features.Get<IExceptionHandlerPathFeature>();
var error = feature?.Error;
var result = new ResultObject(500, error.Message);
if (error != null)
{
_logger.LogError($"系統出現錯誤:{error.Message}-{error.StackTrace}");
}
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
});
});
API請求日志記錄
1、ApiLogFilter
public class ApiLogFilter : IAsyncActionFilter
{
private readonly ILogger logger;
public ApiLogFilter(ILogger<ApiLogFilter> logger)
{
this.logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
string actionArguments = context.ActionArguments.ToJson();
var resultContext = await next();
string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString;
string method = resultContext.HttpContext.Request.Method;
dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic;
string response = JsonConvert.SerializeObject(result.Value);
logger.LogInformation($"URL:{url} \n " +
$"Method:{method} \n " +
$"ActionArguments:{actionArguments}\n " +
$"Response:{response}\n ");
}
}
2、Startup ConfigureServices
services.AddMvc(options =>
{
options.Filters.Add(typeof(ApiLogFilter));
});
轉載記錄:https://www.cnblogs.com/xiangxiufei/p/13337926.html
