忽略 ASP.NET MVC 中的路由会导致 200 而不是 404
形式的 URL
http://site/controller.mvc/action
如果我们不小心将图像的相对 URL 写入 html(例如 src="imgs/img1.gif"
),则会导致浏览器发出请求:
http://site/controller.mvc/action/imgs/img1.gif
我们有以下 路由到控制器,但随后无法解析为操作方法。
这很好,只是我们宁愿使用路由来防止这种情况发生(这样 TempData 就不会被清空等等)。
但是,如果我们添加自定义约束来阻止这种情况发生(使用正则表达式),我们会得到 200 和空响应,而不是预期的 404。有什么想法吗?
We have URLs of the form
http://site/controller.mvc/action
If we accidentally write a relative URL for an image into the html (say src="imgs/img1.gif"
) this results in the browser making a request to:
http://site/controller.mvc/action/imgs/img1.gif
Which gets routed through to the controller but then cannot resolve to an action method.
This is fine except we would rather use routing to prevent this ever happening (so TempData doesn't get emptied and whatever).
However if we put a custom constraint in to stop this happening (using Regular Expressions) we get a 200 and an empty response rather than the expected 404. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我总是在图像前加上 HttpRuntime.AppDomainAppVirtualPath
像这样;
另外我认为你的 imgs 文件夹需要位于 Content 文件夹下。
其快捷方式实际上是“~”(波形符)字符,但我更喜欢将其写出来。
您还可以创建一个静态变量来保存这个值,
然后在您的页面上这样做,
这比编写一个助手来返回一个简单的字符串要容易得多。
I always prefix my images with HttpRuntime.AppDomainAppVirtualPath
Like this;
Also I think your imgs folder needs to be under the Content folder.
The shortcut to this is actually the "~" (tilde) character, but I prefer to write it out.
You could also create a static variable to hold this value,
Then on you page do it this way,
This is much easier than writting a helper to return a simple string.
我建议您使用辅助方法,然后确保在路径前面添加斜杠(例如“/content/img/img1.gif”)。
请参阅提示 #2 http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx
I'd suggest you'll use a helper method, and then from there make sure to stick a slash in front of the paths (e.g. "/content/img/img1.gif").
See tip #2 at http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx