如果 MVC 路由失败,如何重定向到其他页面

How to Redirect to other page if MVC Routing fails

这是我的 RouteConfig.cs,我正在使用 isValidAppId class 来匹配 url 中的 appid 和 'modelApplicationId'我存储在 web.config

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

            routes.MapRoute(
               "ApplicationRoute",
               "{appId}/{controller}/{action}/{id}",
               new { controller = "Account", action = "SignIn", id = UrlParameter.Optional },
               new {
                   isValidAppId = new isValidAppId() 
               }
           );
        }
    }

    public class isValidAppId : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var isValid = false;
            if (values["appId"] != null && WebConfigurationManager.AppSettings["ModelApplicationId"] != null)
            {
                if (values["appId"].ToString() == WebConfigurationManager.AppSettings["ModelApplicationId"].ToString())
                    return isValid = true;
            }

            // return true if this is a valid AppId
            return isValid;
        }
    }

如果 isValidAppId returns false 我想重定向到其他 Error.cshtml 页面。

您可以通过多种方式进行,这取决于您喜欢或需要什么。您可以使用 httpContext 重定向到您想要的页面。您可以使用 HttpContext.Response 对象的某些重定向方法。

以防万一,如果 isValidAppId returns false 那么您只需 throw an custom Exception / HttpException 即可自动重定向至 Error.cshtml 页面并显示您的自定义错误消息。

if(!isValid) // If isValid is false
{
   throw new HttpException(404, "NotFound"); // Modify According to your custom message.
}

// return true if this is a valid AppId
return isValid;

更新:

为了重定向到Error.cshtml页面。只需按照以下代码...

我已经创建了错误控制器:

public class ErrorController : Controller
{
    public ActionResult Error()
    {
        return View();
    }
}

我在 Global.asax.cs

中有以下代码
protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Response.Clear();
    Response.Redirect("/Error/Error");
}

我在我的 MVC 项目的 共享文件夹 中创建了 Error.Cshtml

@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Error";
}

<hgroup class="title">
    <h1 class="error">Error.</h1>
    <h2 class="error">An error occurred while processing your request.</h2>
</hgroup>

希望对您有所帮助...