【问题标题】:Handle Custom error on asp mvc 5 when potentially dangerous occurred发生潜在危险时处理 asp mvc 5 上的自定义错误
【发布时间】:2017-12-09 08:27:04
【问题描述】:

当我在 url 地址中有 : 时出现以下错误:

从客户端检测到有潜在危险的 Request.Path 值 (:)

我希望当我的应用程序出错时,我可以重定向到 /Error/NotFound 操作,但有时它不会发生。

例如,我有以下用于处理自定义错误的代码,它可以正常工作,但是当我遇到潜在危险错误时,controller.Execute() 不会触发。

 protected void Application_Error()
    {
        var lastException = Server.GetLastError();

        if (lastException.GetType() != typeof(HttpException))
            return;

        var httpException = lastException as HttpException;
        var routeData = new RouteData();
        routeData.Values.Add("controller", "Error");

        if (httpException?.GetHttpCode() == 404 || httpException?.GetHttpCode() == 400)
            routeData.Values.Add("action", "NotFound");

        if (routeData.Values.Count <= 1)
            return;

        try
        {
            IController controller = new ErrorController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine(e.Message);
            throw new NullReferenceException();
        }
    }

我意识到当发生潜在危险错误时,我的上下文的某些属性(例如CurrentNotification, Handler, Items, Profile, Session and User)为空。我不知道我的上下文是否与这个问题有关。

这是我的网络配置:

<system.web>
    <compilation debug="true" targetFramework="4.6.2" />
    <httpRuntime targetFramework="4.6.2" maxRequestLength="314572800" enableVersionHeader="false" requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
       <remove statusCode="404" />
       <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
    </httpErrors>
</system.webServer>

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    您可以像这样处理 Web.Config 中的所有类型的错误:

      <customErrors mode="On"  defaultRedirect="~/Error/ErrorPage/404" >
          <error statusCode="404" redirect="~/Error/ErrorPage/404" />
          <error statusCode="403" redirect="~/Error/ErrorPage/403" />
          <error statusCode="500" redirect="~/Error/ErrorPage/500" />
        </customErrors>
    

    我添加的是

    默认重定向

    处理任何类型的错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      相关资源
      最近更新 更多