asp.net mvc: 当路由不匹配时我们可以设置http状态码吗
asp.net mvc: Can we set http status code when route does not match
假设这是我的路线,需要 productid 的整数数据
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = @"\d+" }
);
所以这些路线可行
/Product/3
/Product/8999
我怎样才能将用户重定向到一个预先存在的视图,在该视图中我可以针对这种情况显示友好的错误消息?
还有一件事我想知道,当用户输入 /Product/apple
并且这条路线不匹配时,我们可以设置状态代码吗?所以在这种情况下,我喜欢设置 statusCode="404"
。如果我能做到,那么在 customErrors
下面我指定的视图将显示 404 错误。建议我怎么做?
<customErrors mode="Off" defaultRedirect="~/error.html">
<error statusCode="403" redirect="~/access-denied.aspx" />
<error statusCode="404" redirect="~/page-not-found.aspx" />
<error statusCode="500" redirect="~/error.html" />
</customErrors>
如果可以,请指导我。
您当前列出的路线与您所说的请求不匹配。
您应该考虑像这样添加两条路线。
routes.MapRoute(
"Product",
"Product/{productId}",
new { controller = "Product", action = "Details" },
new { productId = @"\d+" }
);
routes.MapRoute(
"ProductNotMatched",
"Product/{productId}",
new { controller = "Product", action = "NotFound" });
当 /Product/apple
被击中时,这将调用 NotFound
动作。
接下来你可以创建一个动作并像这样重定向它,
public ActionResult NotFound()
{
return HttpNotFound();
**// HERE you can redirect to specific html / razor view or static page as you wish**
}
希望对您有所帮助
假设这是我的路线,需要 productid 的整数数据
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = @"\d+" }
);
所以这些路线可行
/Product/3
/Product/8999
我怎样才能将用户重定向到一个预先存在的视图,在该视图中我可以针对这种情况显示友好的错误消息?
还有一件事我想知道,当用户输入 /Product/apple
并且这条路线不匹配时,我们可以设置状态代码吗?所以在这种情况下,我喜欢设置 statusCode="404"
。如果我能做到,那么在 customErrors
下面我指定的视图将显示 404 错误。建议我怎么做?
<customErrors mode="Off" defaultRedirect="~/error.html">
<error statusCode="403" redirect="~/access-denied.aspx" />
<error statusCode="404" redirect="~/page-not-found.aspx" />
<error statusCode="500" redirect="~/error.html" />
</customErrors>
如果可以,请指导我。
您当前列出的路线与您所说的请求不匹配。
您应该考虑像这样添加两条路线。
routes.MapRoute(
"Product",
"Product/{productId}",
new { controller = "Product", action = "Details" },
new { productId = @"\d+" }
);
routes.MapRoute(
"ProductNotMatched",
"Product/{productId}",
new { controller = "Product", action = "NotFound" });
当 /Product/apple
被击中时,这将调用 NotFound
动作。
接下来你可以创建一个动作并像这样重定向它,
public ActionResult NotFound()
{
return HttpNotFound();
**// HERE you can redirect to specific html / razor view or static page as you wish**
}
希望对您有所帮助