ASP.Net MVC-处理错误的URL参数 [英] ASP.Net MVC - handling bad URL parameters

查看:139
本文介绍了ASP.Net MVC-处理错误的URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理访客构建自己的URL并将其期望的ID替换为他们喜欢的任何东西的最佳方法是什么?

What's the best way to handle a visitor constructing their own URL and replacing what we expect to be an ID with anything they like?

例如:

ASP.Net MVC-处理错误的URL参数

但是用户可以轻松地将URL替换为:

But the user could just as easily replace the URL with:

https://stackoverflow.com/questions/foo

我已经考虑过将每个Controller Function参数都设置为String,并在它们上使用Integer.TryParse()-如果通过,则我具有一个ID并且可以继续,否则我可以将用户重定向到Unknown/not-找到或索引视图.

I've thought of making every Controller Function parameter a String, and using Integer.TryParse() on them - if that passes then I have an ID and can continue, otherwise I can redirect the user to an Unknown / not-found or index View.

Stack Overflow可以很好地处理它,我也想这样做-您如何做到这一点,或者您会提出什么建议?

Stack Overflow handles it nicely, and I'd like to too - how do you do it, or what would you suggest?

推荐答案

下面是像您这样的路线示例,但对数字有限制:

Here's an example of a route like yours, with a constraint on the number:

routes.MapRoute(
    "Question",
    "questions/{questionID}",
    new { controller = "StackOverflow", action = "Question" },
    new { questionID = @"\d+" } //Regex constraint specifying that it must be a number.
);

在这里,我们将questionID设置为至少一个数字.这还将阻止除整数以外的所有url,并避免需要可为null的int.

Here we set the questionID to have at least one number. This will also block out any urls containing anything but an integer, and also prevents the need for a nullable int.

注意:这不考虑大于Int32范围(-2147483647-+2147483647)的数字.我将其留给用户解决. :)

Note: This does not take into account numbers that larger than the range of Int32 (-2147483647 - +2147483647). I leave this as an exercise to the user to resolve. :)

如果用户输入url"questions/foo",则他们将不会点击"Question"操作,并且会失败,因为它无法通过参数约束.如果需要,您可以采用全包/默认路由对其进行进一步处理:

If the user enters the url "questions/foo", they will not hit the Question action, and fall through it, because it fails the parameter constraint. You can handle it further down in a catchall/default route if you want:

routes.MapRoute(
    "Catchall",
    "{*catchall}", // This is a wildcard routes
    new { controller = "Home", action = "Lost" }
);

这会将用户发送到Home控制器中的Lost操作.有关通配符的更多信息,请参见此处.

This will send the user to the Lost action in the Home controller. More information on the wildcard can be found here.

注意:Catchall应该作为LAST路由存在.鉴于ASP.NET MVC中路由的惰性,将其放置在链的最上方将意味着它将处理它下面的所有其他路由.

NB: The Catchall should reside as the LAST route. Placing it further up the chain will mean that this will handle all others below it, given the lazy nature of routes in ASP.NET MVC.

这篇关于ASP.Net MVC-处理错误的URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆