zoukankan      html  css  js  c++  java
  • MVC Filter自定义异常(拦截)

     1 // -----------------------------------------------------------------------
     2 //  <copyright file="CustomExceptionAttribute.cs" company="技术支持——谭明超">
     3 //      Copyright (c) 2016 QS.Web.Extensions. All rights reserved.
     4 //  </copyright>
     5 //  <last-editor>谭明超</last-editor>
     6 //  <last-date>2016/8/2 20:56:16</last-date>
     7 // -----------------------------------------------------------------------
     8 
     9 using System;
    10 using System.Web;
    11 using System.Web.Mvc;
    12 
    13 namespace QS.Web.Extensions
    14 {
    15     public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
    16     {
    17         public void OnException(ExceptionContext filterContext)
    18         {
    19             Exception exception = filterContext.Exception;
    20             if (filterContext.ExceptionHandled == true)
    21             {
    22                 return;
    23             }
    24             HttpException httpException = new HttpException(null, exception);
    25             //filterContext.Exception.Message可获取错误信息
    26 
    27             /*
    28              * 1、根据对应的HTTP错误码跳转到错误页面
    29              * 2、这里对HTTP 404/400错误进行捕捉和处理
    30              * 3、其他错误默认为HTTP 500服务器错误
    31              */
    32             if (httpException != null && (httpException.GetHttpCode() == 400 || httpException.GetHttpCode() == 404))
    33             {
    34                 filterContext.HttpContext.Response.StatusCode = 404;
    35                 filterContext.HttpContext.Response.Write("错误的请求路径");
    36                 filterContext.HttpContext.Response.WriteFile("~/HttpError/404.html");
    37             }
    38             else
    39             {
    40                 filterContext.HttpContext.Response.StatusCode = 500;
    41                 filterContext.HttpContext.Response.Write("服务器内部错误");
    42                 filterContext.HttpContext.Response.WriteFile("~/HttpError/500.html");
    43             }
    44             /*---------------------------------------------------------
    45              * 这里可进行相关自定义业务处理,比如日志记录等
    46              ---------------------------------------------------------*/
    47 
    48             //设置异常已经处理,否则会被其他异常过滤器覆盖
    49             filterContext.ExceptionHandled = true;
    50 
    51             //在派生类中重写时,获取或设置一个值,该值指定是否禁用IIS自定义错误。
    52             filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    53         }
    54     }
    55 }
    View Code

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

  • 相关阅读:
    Linux命令(一)
    数据库SQL学习(一)
    Eclipse
    VsCode支持的markdown语法参考(一)
    常用算法Tricks(一)
    dispose方法的使用
    收藏一个链接
    我还不知道取什么名字
    NioSocket的用法
    随便乱塞塞2~
  • 原文地址:https://www.cnblogs.com/Tmc-Blog/p/5737886.html
Copyright © 2011-2022 走看看