Asp.net ASP MVC-如何更改url.Content请求的基本url?
假设我有一个带有以下url的请求: foo.bar.com/do/something “do”控制器的“something”操作返回一个具有以下url的图像的视图:foo.bar.com/content/image.png(由助手url.content生成)-这只是一个示例,我的实际页面有很多图像Asp.net ASP MVC-如何更改url.Content请求的基本url?,asp.net,asp.net-mvc,Asp.net,Asp.net Mvc,假设我有一个带有以下url的请求: foo.bar.com/do/something “do”控制器的“something”操作返回一个具有以下url的图像的视图:foo.bar.com/content/image.png(由助手url.content生成)-这只是一个示例,我的实际页面有很多图像 我想知道我可以在操作中做些什么来更改Url.Content的行为,以便它使用Urllocalhost/Content/image.png生成我的图像Url这可能不是最好的解决方案,但它可能适合您: 您
我想知道我可以在操作中做些什么来更改Url.Content的行为,以便它使用Urllocalhost/Content/image.png生成我的图像Url这可能不是最好的解决方案,但它可能适合您: 您可以编写如下扩展来实现这一点:
// Determine if gen localhost or the normal hostname
public static bool IsUseLocalhost { get; set; }
public static string ContentFullPath(this UrlHelper url
, string virtualPath, string schema = "", string host = "")
{
var result = string.Empty;
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
if (string.IsNullOrEmpty(schema))
{
schema = requestUrl.Scheme;
}
if (string.IsNullOrEmpty(host))
{
if (IsUseLocalhost)
{
host = "localhost";
}
else
{
host = requestUrl.Authority;
}
}
result = string.Format("{0}://{1}{2}",
schema,
host,
VirtualPathUtility.ToAbsolute(virtualPath));
return result;
}
在该操作中,您可以将静态IsUseLocalhost
设置为true
,以使用localhost打开所有gen url
然后在视图中,将其用作:
@Url.ContentFullPath("~/content/image.png")
@Url.ContentFullPath("~/content/image.png", host: "localhost")
如果要设置显式主机,请在视图中将其用作:
@Url.ContentFullPath("~/content/image.png")
@Url.ContentFullPath("~/content/image.png", host: "localhost")