简体   繁体   English

如何将错误重定向到MVC主页?

[英]How to redirect errors to home page in MVC?

I'm trying to get my website when I'm on the root page to automatically default back to the homepage if I type in a bad URL, how do I do this in MVC? 如果我输入的URL错误,那么我要进入根目录页面时会自动将其默认返回首页,该如何在MVC中做到这一点?

I'm just learning MVC and can't figure this out... I have this: 我只是在学习MVC,无法弄清楚...我有这个:

namespace DvdApplication
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Dvd", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

You can easily achieve that using web.config or HandleError Attribute: 您可以使用web.config或HandleError属性轻松实现:

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="401" subStatusCode="-1" />
      <error statusCode="401" path="/Error/Forbidden" responseMode="ExecuteURL" />
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="500" path="/Error/Generic" responseMode="ExecuteURL" />
      <remove statusCode="501" subStatusCode="-1" />
      <error statusCode="501" path="/Error/Generic" responseMode="ExecuteURL" />
    </httpErrors>
</system.webServer>

PS: note that should exist a controller "Error" and actions "Forbidden", "NotFound" and "Generic". PS:请注意,应该存在一个控制器“错误”和操作“禁止”,“未找到”和“通用”。

or 要么

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]] [HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")]] [HandleError(ExceptionType = typeof(SqlException),视图=“ DatabaseError”)]] [HandleError(ExceptionType = typeof(NullReferenceException),视图=“ LameErrorHandling”)]]

more info: 更多信息:

http://weblogs.asp.net/scottgu/asp-net-mvc-preview-4-release-part-1 http://weblogs.asp.net/scottgu/asp-net-mvc-preview-4-release-part-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM