using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using System;
using System.IO;
using System.Threading.Tasks;
using YBDevice.Core;
namespace YBDevice.NApi
{
///
/// 异常处理中间件
///
//public class MyExceptionMiddleware
//{
// private readonly RequestDelegate _next;
// public MyExceptionMiddleware(RequestDelegate next)
// {
// _next = next;
// }
// public async Task Invoke(HttpContext httpContext)
// {
// try
// {
// await _next(httpContext);
// }
// catch (Exception ex)
// {
// // new ApiLoggerApplication().InsertErrorLog(ex);
// await HandleExceptionAsync(httpContext, ex);
// }
// }
// private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
// {
// //记录日志
// // new ApiLoggerApplication().InsertErrorLog(ex);
// return Task.CompletedTask;
// }
// public void OnException(ExceptionContext context)
// {
// context.ExceptionHandled = true;
// }
//}
/////
///// Extension method used to add the middleware to the HTTP request pipeline.
/////
//public static class MyExceptionMiddlewareExtensions
//{
// public static IApplicationBuilder UseMyExceptionMiddleware(this IApplicationBuilder builder)
// {
// return builder.UseMiddleware();
// }
//}
public static class ExceptionHandlingExtensions
{
public static void UseMyExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
var ex = context.Features.Get();
//如果是用户取消的异常,则不必记录到日志
if (context.RequestAborted.IsCancellationRequested && (ex is TaskCanceledException || ex is OperationCanceledException))
{
Console.WriteLine("用户取消了操作");
}
else
{
if (ex != null)
{
var request = context.Request;
var action = request.Path.Value;
var query_string = request.QueryString.Value;
if (request.Method == "POST" && request.ContentLength > 0)
{
request.EnableBuffering();
request.Body.Position = 0;
using (var sr = new StreamReader(request.Body))
{
query_string = await sr.ReadToEndAsync();
}
}
//获取token
var token = request.Headers["token"];
if (!string.IsNullOrEmpty(token))
{
query_string = $"{query_string}\r\ntoken={token}";
}
var _logger = App.GetService();
//记录日志
_logger.AddErrorLogger(ex.Error, query_string, action);
}
}
var result = new ResultInfo { code = ResultState.SYSTEMERROR, message = ex?.Error?.Message ?? "系统异常" };
context.Response.StatusCode = 200;
await context.Response.WriteAsync(result.ToJson());
});
});
}
}
}