如何将所有无效URL重定向到某个操作(How to redirect all invalid URLs to some action)

编程入门 行业动态 更新时间:2024-10-27 02:31:09
如何将所有无效URL重定向到某个操作(How to redirect all invalid URLs to some action)

我有一个带有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将返回404

Constrain 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

本文发布于:2023-07-28 19:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308212.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   重定向   操作   URL   action

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!