【问题标题】:How do you use custom errors and preserve the response code?您如何使用自定义错误并保留响应代码?
【发布时间】:2015-02-15 05:56:55
【问题描述】:

在我的 web.config 中,您可以看到 redirectMode="ResponseRewrite"。我读到这是我需要保留状态代码的内容。不幸的是,一旦我把它放进去,我就会得到:

“处理您的请求时发生异常。此外,在执行第一个异常的自定义错误页面时发生另一个异常。请求已终止。”

省略此变量成功将我重定向到 ~/Error/Index.cshtml,但响应为 200.doh。任何方向都将不胜感激,谢谢。

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error/Index">
      <error statusCode="404" redirect="~/Error/Index"/>
      <error statusCode="500" redirect="~/Error/Index"/>
    </customErrors>
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL">
      <remove statusCode="403"/>
      <remove statusCode="404"/>
      <remove statusCode="500"/>
      <error statusCode="403" path="~/Error/Index" responseMode="File"/>
      <error statusCode="404" path="~/Error/Index" responseMode="File"/>
      <error statusCode="500" path="~/Error/Index" responseMode="File"/>
    </httpErrors>
  </system.webServer>

在我的 filterconfig.cs 中:

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            // does this conflict?
            filters.Add(new HandleErrorAttribute());
        }
    }

【问题讨论】:

    标签: c# asp.net-mvc-5


    【解决方案1】:

    不记得我在哪里看到了这段代码,或者我做了什么更改,但它在我的 MVC Web 应用程序中运行良好

    Web.config

    <system.web>
        <compilation debug="true" targetFramework="4.5.1" />
        <httpRuntime targetFramework="4.5.1" />
        <customErrors mode="Off" />
      </system.web>
    

    全球.aspx

    protected void Application_EndRequest(Object sender, EventArgs e)
            {
                ErrorConfig.Handle(Context);
            }
    

    ErrorConfig.cs

    namespace Web.UI.Models.Errors
    {
        public static class ErrorConfig
        {
            public static void Handle(HttpContext context)
            {
                switch (context.Response.StatusCode)
                {
                    case 401:
                        Show(context, 401);
                        break;
                    case 404:
                        Show(context, 404);
                        break;
                    case 500:
                        Show(context, 500);
                       break;
                }
            }
            //TODO uncomment 500 error
            static void Show(HttpContext context, Int32 code)
            {
                context.Response.Clear();
    
                var w = new HttpContextWrapper(context);
                var c = new ErrorController() as IController;
                var rd = new RouteData();
    
                rd.Values["controller"] = "Error";
                rd.Values["action"] = "Index";
                rd.Values["id"] = code.ToString(CultureInfo.InvariantCulture);
    
                c.Execute(new RequestContext(w, rd));
            }
        }
    }
    

    错误控制器

    public class ErrorController : Controller
        {
            // GET: Error
            [HttpGet]
            public ViewResult Index(Int32? id)
            {
                var statusCode = id.HasValue ? id.Value : 500;
                var error = new HandleErrorInfo(new Exception("An exception with error " + statusCode + " occurred!"), "Error", "Index");
    
                int errorCode = statusCode;
                ViewBag.error = errorCode;
                return View("Error");
            }
        }
    

    错误视图模型

    namespace Web.UI.Models.Errors
    {
        public class ErrorViewModel
        {
            public string DisplayErrorMessage   { get; set; }
            public string DisplayErrorPageTitle { get; set; }
        }
    }
    

    然后在共享文件夹错误页面添加

    @model Web.UI.Models.Errors.ErrorViewModel
    
    @{
        int errorCode = Convert.ToInt32(@ViewBag.error);
    
    
        switch (errorCode)
        {
            case 404:
                ViewBag.Title = "404 Page Not Found";
                Html.RenderPartial("~/Views/Shared/ErrorPages/HttpError404.cshtml");
                break;
            case 500:
                ViewBag.Title = "Error Occurred";
                Html.RenderPartial("~/Views/Shared/_Error.cshtml");
                break;
            default:
                ViewBag.Title = @Model.DisplayErrorPageTitle;
                Html.RenderPartial("~/Views/Shared/ErrorPages/HttpNoResultsFound.cshtml");
                break;
        }
    } 
    

    以上页面未找到返回404状态,错误返回500,希望对您有所帮助

    【讨论】:

    • 不错的解决方案,但这样做的缺点是您将无法在开发过程中获得详细的错误消息。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多