【问题标题】:MVC error page controller and custom routingMVC 错误页面控制器和自定义路由
【发布时间】:2014-03-07 22:16:53
【问题描述】:

我已修改路由以在 URL 中包含文化

routes.MapRoute(
            name: "Default",
            url: "{culture}/{controller}/{action}/{id}",
            defaults: new { culture = "en-GB", controller = "StyleGuide", action = "Template", id = UrlParameter.Optional },
            constraints: new { culture = @"[a-z]{2}-[A-Z]{2}" }
        );

我还创建了ErrorController 并在Web.config 中定义了我的错误页面:

<customErrors mode="On" defaultRedirect="~/Error/Index">
  <error statusCode="404" redirect="~/Error/NotFound"/>
</customErrors>

我也在使用 mvcSiteMapProvider,所以我已经包含了我的新错误页面,并且能够通过菜单访问它们,因为它使用包含我的文化的 URL:localhost/en-GB/Error/NotFound

当抛出异常时,由于Web.Config 中定义的重定向中缺少文化,因此找不到错误页面。

在重定向到我的错误页面时如何包含文化?

【问题讨论】:

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


    【解决方案1】:

    这是一篇很好的文章,描述了 ASP.NET MVC 中错误处理方法的可能性和限制:Exception Handling in ASP.NET MVC

    如果您不需要控制器或动作级别的异常处理,您可以在Application_Error 事件中进行错误处理。您可以在 web.config 中关闭自定义错误,并在此事件中进行日志记录和错误处理(包括重定向到正确的页面)。

    类似的东西:

    protected void Application_Error(object sender, EventArgs e) 
    {  
        Exception exception = Server.GetLastError();
        Response.Clear();
    
        HttpException httpException = exception as HttpException;  
    
        string action = string.Empty;    
    
        if (httpException != null)
        {
            switch (httpException.GetHttpCode())
            {
                case 404:
                    // page not found 
                    action = "NotFound";
                    break;
                //TODO: handle other codes
                default:
                    action = "general-error";
                    break;
            }
        }
        else
        {
            //TODO: Define action for other exception types
            action = "general-error";
        }
    
        Server.ClearError();
    
        string culture = Thread.CurrentThread.CurrentCulture.Name;    
    
        Exception exception = Server.GetLastError();
        Response.Redirect(String.Format("~/{0}/error/{1}", culture, action));
    }
    

    【讨论】:

    • 我会尽快查看并回复您 - 感谢您的回答!
    • 感谢您如此及时地回复他们
    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多