这是我的RouteConfig.cs
,我正在使用isValidAppId
课程来匹配appid
中的url
与' 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返回false 我想重定向到其他Error.cshtml
页。
答案 0 :(得分:0)
答案 1 :(得分:0)
如果是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>
我希望这会有所帮助......