我有一个带有Index()和Foo(int id)动作和路由的Home控制器,如下所示:
routes.MapRoute("Foo", "{id}", new { controller = "Home", action = "Foo" }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults );所以像/和/123这样的URL就像他们应该做的那样工作。 但是当URL为/blahblah ,其中blahblah不是有效的动作名称时,我得到错误
参数字典包含非可空类型'System.Int32'的参数'id'的空条目
这当然是正常的,因为Foo动作得到int参数而不是int?
问题是我不能使用int,因为那么Index和Foo动作都匹配/ URL,所以还有额外的不必要的Foo调用。
所以问题是,是否有可能捕获上面的异常或将所有无效的URL(如/blahblah重定向到其他一些操作。
I have a Home controller with Index() and Foo(int id) actions and routings like these:
routes.MapRoute("Foo", "{id}", new { controller = "Home", action = "Foo" }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults );So URLs like / and /123 work as they are supposed to do. However when the URL is /blahblah where blahblah is not a valid action name I get the error
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'
which is normal of course because the Foo action gets int parameter instead of int?
The problem is I can't use int, because then both the Index and Foo actions match / URL, so there is additional unnecessary Foo call.
So the question is, is it possible to catch the exception above OR redirect all not valid URLs like /blahblah to some other action.
最满意答案
将Foo路由定义中的id标记约束为数字:
routes.MapRoute( "Foo", "{id}", new { controller = "Home", action = "Foo" }, new { id = @"\d+" } );现在:
/将击中HomeController/Index /123将命中HomeController/Foo并传递id = 123作为参数 /foobar将返回404Constrain the id token on your Foo route definition to a number:
routes.MapRoute( "Foo", "{id}", new { controller = "Home", action = "Foo" }, new { id = @"\d+" } );Now:
/ will hit HomeController/Index /123 will hit HomeController/Foo and pass id = 123 as argument /foobar will return a 404更多推荐
Foo,URL,int,action,动作,电脑培训,计算机培训,IT培训"/> <meta name="descrip
发布评论