忽略 ASP.NET MVC 中的路由会导致 200 而不是 404

发布于 2024-08-03 09:32:38 字数 397 浏览 3 评论 0原文

形式的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘和柠 2024-08-10 09:32:38

我总是在图像前加上 HttpRuntime.AppDomainAppVirtualPath

像这样;

background="<%=HttpRuntime.AppDomainAppVirtualPath %>/Content/images/aqua.jpg"

另外我认为你的 imgs 文件夹需要位于 Content 文件夹下。

src="/content/imgs/img1.gif

其快捷方式实际上是“~”(波形符)字符,但我更喜欢将其写出来。

src="~/content/imgs/img1.gif"

您还可以创建一个静态变量来保存这个值,

public static string VP = HttpRuntime.AppDomainAppVirtualPath;

然后在您的页面上这样做,

background="<%=VP%>/Content/images/aqua.jpg"

这比编写一个助手来返回一个简单的字符串要容易得多。

I always prefix my images with HttpRuntime.AppDomainAppVirtualPath

Like this;

background="<%=HttpRuntime.AppDomainAppVirtualPath %>/Content/images/aqua.jpg"

Also I think your imgs folder needs to be under the Content folder.

src="/content/imgs/img1.gif

The shortcut to this is actually the "~" (tilde) character, but I prefer to write it out.

src="~/content/imgs/img1.gif"

You could also create a static variable to hold this value,

public static string VP = HttpRuntime.AppDomainAppVirtualPath;

Then on you page do it this way,

background="<%=VP%>/Content/images/aqua.jpg"

This is much easier than writting a helper to return a simple string.

坚持沉默 2024-08-10 09:32:38

我建议您使用辅助方法,然后确保在路径前面添加斜杠(例如“/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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文