ASP.NET MVC:jQuery 地址阻止用户导航到直接 URL
我们正在开发一个 Ajax 应用程序,并利用 jQuery Address 插件来加载应用程序的各个页面,因此我们网站的 url 如下所示:www.app.com#/SomeController/SomeAction。导航到这样的 url 会加载应用程序的默认路由,然后利用 jQuery Address 将 SomeController/SomeAction url 加载到页面上的 div 中。
问题是用户仍然可以通过在浏览器中输入 url 直接访问 www.app.com/SomeController/SomeAction (无井号)。我们如何阻止用户直接访问页面并要求他们在那里有哈希登录以确保页面是通过 Ajax 请求加载的?
We are developing an Ajax application and are utilizing the jQuery Address plugin to load the various pages of the application So the urls for our site look like: www.app.com#/SomeController/SomeAction. Navigating to such a url loads the default route for the application and then jQuery Address is utilized to load the SomeController/SomeAction url into a div on the page.
The problem is that the user can still access www.app.com/SomeController/SomeAction (no hash sign) directly by typing the url in the browser. How do we prevent the user from being able to access the pages directly and require that they have the hash sign in there to make sure the pages are loaded via Ajax request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个要添加到默认路由之前的路由,如下所示:
该路由将处理任何不以哈希字符开头的请求。任何以哈希字符开头的请求都将无法满足路由约束,并将继续执行您的默认路由。
创建一个控制器和操作来显示 404 页面或某些自定义错误页面,然后就完成了。
Create a route to add prior to your default route, like so:
This route will handle any request which does not start with a hash character. Any request starting with a hash character will fail the route constraint, and will go on to your default route.
Create a controller and action to show a 404 page, or some custom error page, and you are set.
您可以创建一个检查 request.isajaxrequest() 的过滤器。除了默认路由之外,您拒绝任何不存在的请求。
我不确定这是否是最好的方法。
You could create a filter that checked request.isajaxrequest(). You reject any requested that aren't, apart from on the default route.
I'm not sure if it's the best way though.
coachlorben 是正确的,您可以使用路由技巧来尝试限制合法客户端或应用程序请求特定资源的方式,但您永远无法保护自己免受伪造(使用 fiddler 或其他工具)。 coachlorben 提出的方法仅适用于避免用户混淆并限制应用程序的“API”区域。当然,您实际上不应该拥有一个仅依赖于 # 深层链接的应用程序,因为这会导致 SEO 等问题。但这是一个不同的讨论。
另一种方法,而不是过滤器,您可以将以下内容添加到您的操作方法
标准实践中,为锚点提供一个空或虚拟的 href 属性,并让单击事件执行 AJAX 回调?这样,如果用户复制超链接,他就会自动获得正确的 URL。
counsellorben is correct, you can do routing tricks to try to limit the way legitimate clients or apps request a particular resource but you’ll never be able to protect yourself from the forging (With fiddler or another tool). The approach proposed by counsellorben is only useful to potentially avoid user confusion and limit the “API” area of an app. Of course, you shouldn’t actually have an app that only depends on # deep links because that causes problems with SEO etc. But that’s a different discussion.
Another approach, rather than a filter, you can add the following to your action method
standard practice here to give the anchor an empty or dummy href property and to have the click event perform the AJAX callback? That way, if a user copies the hyperlink he is just automatically given the correct URL.