MVC Filter自定义异常(拦截)

 // -----------------------------------------------------------------------
// <copyright file="CustomExceptionAttribute.cs" company="技术支持——谭明超">
// Copyright (c) 2016 QS.Web.Extensions. All rights reserved.
// </copyright>
// <last-editor>谭明超</last-editor>
// <last-date>2016/8/2 20:56:16</last-date>
// ----------------------------------------------------------------------- using System;
using System.Web;
using System.Web.Mvc; namespace QS.Web.Extensions
{
public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
Exception exception = filterContext.Exception;
if (filterContext.ExceptionHandled == true)
{
return;
}
HttpException httpException = new HttpException(null, exception);
//filterContext.Exception.Message可获取错误信息 /*
* 1、根据对应的HTTP错误码跳转到错误页面
* 2、这里对HTTP 404/400错误进行捕捉和处理
* 3、其他错误默认为HTTP 500服务器错误
*/
if (httpException != null && (httpException.GetHttpCode() == || httpException.GetHttpCode() == ))
{
filterContext.HttpContext.Response.StatusCode = ;
filterContext.HttpContext.Response.Write("错误的请求路径");
filterContext.HttpContext.Response.WriteFile("~/HttpError/404.html");
}
else
{
filterContext.HttpContext.Response.StatusCode = ;
filterContext.HttpContext.Response.Write("服务器内部错误");
filterContext.HttpContext.Response.WriteFile("~/HttpError/500.html");
}
/*---------------------------------------------------------
* 这里可进行相关自定义业务处理,比如日志记录等
---------------------------------------------------------*/ //设置异常已经处理,否则会被其他异常过滤器覆盖
filterContext.ExceptionHandled = true; //在派生类中重写时,获取或设置一个值,该值指定是否禁用IIS自定义错误。
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
}

该源码源自网上,,,,不记得哪里的了

上一篇:Maven 上传 jar包 到私服


下一篇:webapi 发布接口报405错误(angularjs2.0)