General.Web/Filters/GlobalExceptionFilter.cs
(完整代码) 1KBusing Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
namespace General.Mvc.Filters
{
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly IWebHostEnvironment _env;
private readonly Serilog.ILogger logger;
public GlobalExceptionFilter(IWebHostEnvironment env, Serilog.ILogger logger)
{
_env = env;
this.logger = logger;
}
public void OnException(ExceptionContext context)
{
Exception exception = context.Exception;
string error = string.Empty;
error += string.Format("{0} | {1} ", exception.StackTrace, exception.InnerException);
var json = new { message = exception.Message, detail = error, code = 0 };
if (_env.IsDevelopment())
{
context.Result = new InternalServerErrorObjectResult(json);
}
else
{
//写入日志
logger.Error(JsonHelper.Serialize(json));
context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Result = new RedirectResult("/Error/500");
}
}
}
public class InternalServerErrorObjectResult : ObjectResult
{
public InternalServerErrorObjectResult(object error) : base(error)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
}
}
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
