public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter //, IAsyncExceptionFilter
{
private readonly IModelMetadataProvider _IModelMetadataProvider;
public CustomExceptionFilterAttribute(IModelMetadataProvider modelMetadataProvider)
{
this._IModelMetadataProvider = modelMetadataProvider;
}
///
/// 当有异常发生的时候,就会触发到这里
///
///
///
public void OnException(ExceptionContext context)
{
if (context.ExceptionHandled == false)
{
//在这里就开始处理异常--还是要响应结果给客户端
//1.页面展示
//2.包装成一个JSON格式
if (IsAjaxRequest(context.HttpContext.Request)) //判断是否是Ajax请求--JSON
{
//JSON返回
context.Result = new JsonResult(new
{
Succeess = false,
Message = context.Exception.Message
});
}
else
{
//返回页面
ViewResult result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
result.ViewData = new ViewDataDictionary(_IModelMetadataProvider, context.ModelState);
result.ViewData.Add("Exception", context.Exception);
context.Result = result; //断路器---只要对Result赋值--就不继续往后了;
}
context.ExceptionHandled = true;//表示当前异常被处理过
}
}
/
/ 当有异常发生的时候,就会触发到这里
/
/
/
/
//public Task OnExceptionAsync(ExceptionContext context)
//{
// throw new NotImplementedException();
//}
private bool IsAjaxRequest(HttpRequest request)
{
//HttpWebRequest httpWebRequest = null;
//httpWebRequest.Headers.Add("X-Requested-With", "XMLHttpRequest");
string header = request.Headers["X-Requested-With"];
return "XMLHttpRequest".Equals(header);
}
}
使用
[TypeFilter(typeof(CustomExceptionFilterAttribute))]
public IActionResult Index7()
{
throw new Exception("其实没啥,就是想要异常一下~~");
}
#region 中间件处理异常
{
///如果Http请求中的Response中的状态不是200,就会进入Home/Error中;
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");//只要不是200 都能进来
//下面这个是自己拼装一个Reponse 输出
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async co服务器托管网ntext =>
{
context.Response.StatusCode = 200;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("rn");
await context.Response.WriteAsync("ERROR!
rn");
var exceptionHandlerPathFeature =
context.Features.Get();
Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
Console.WriteLine($"{exceptionHandlerPathFeature?.Error.Message}");
Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
await context.Response.WriteAsync("File error thrown!
rn");
}
await context.Response.WriteAsync("Home
rn");
await context.Response.WriteAsync("rn");
await context.Response.WriteAsync(new string(' ', 512)); // IE padding
});
});
}
#endregion
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
首先当然是安装go运行环境,安装方法参看: 一、安装 Mercurial Mercurial 是一个跨平台的分布式版本控制软件。Mercurial主要由Python语言实现,不过也包含一个用C实现的二进制比较工具。Mercurial一开始的…