例如,我可以在默认的mvc模板中编写此代码
<a asp-area="" asp-route-returnUrlFoo="foo"
asp-controller="Account" asp-action="RegisterFoo">Register</a>
它会生成错误的网址
/Account/RegisterFoo?returnUrlFoo=foo
当行动名称或路线参数不正确时,是否可能抛出错误?
答案 0 :(得分:0)
您可以添加新路由,将所有无效请求重定向到您自己的特定控制器和操作:
app.UseMvc(routes =>
{
// your other routes here
routes.MapRoute(_
name: "Fallback",
url: "{*any}",
defaults: new { controller = "Error", action = "Handler"});
}
在上述情况下,这会将所有(未定义的)映射到/Error/Handler
。您可以修改它以满足您自己的要求。
您可以在此处阅读有关路线模板的更多信息:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing#route-template-reference
当然,还有另一种方法是在控制器的基础上处理它。这种方法不太通用,可以让您创建更多的目标方法来处理URI /路由错误。
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();