1

我们有表单的 URL

http://site/controller.mvc/action

如果我们不小心将图像的相对 URL 写入 html(比如src="imgs/img1.gif"),这会导致浏览器发出以下请求:

http://site/controller.mvc/action/imgs/img1.gif

它被路由到控制器,但随后无法解析为操作方法。

这很好,除非我们宁愿使用路由来防止这种情况发生(所以 TempData 不会被清空等等)。

但是,如果我们设置一个自定义约束来阻止这种情况发生(使用正则表达式),我们会得到一个 200 和一个空响应,而不是预期的 404。有什么想法吗?

4

2 回答 2

2

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.

于 2009-08-28T11:50:16.803 回答
0

我建议您使用辅助方法,然后确保在路径前添加一个斜杠(例如“/content/img/img1.gif”)。

请参阅http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx上的提示 #2

于 2009-08-28T12:32:15.593 回答