using LiveForum.Code.Base;
using LiveForum.Code.ExceptionExtend;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
namespace LiveForum.Code.MiddlewareExtend
{
///
/// 异常中间件
///
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (ArgumentNullException ex)
{
_logger.LogError($"ArgumentNullException异常记录=>{context.Request.Path.ToString()},{ex.Message}", ex);
// 如果响应已经开始了,就不能再修改响应头或写入内容
if (context.Response.HasStarted)
{
return;
}
context.Response.StatusCode = StatusCodes.Status200OK;
BaseResponse