ASP MVC - 如何更改Url.Content请求的基本URL?

时间:2015-10-18 20:06:54

标签: asp.net asp.net-mvc

假设我有以下网址的请求: 的 foo.bar.com/do/something

“do”控制器的“something”操作返回一个视图,其中包含具有以下URL的图像: foo.bar.com/content/image.png (由帮助程序生成< strong> Url.Content ) - 这只是一个例子,我的实际页面有很多图片

我想知道在操作中我可以做些什么来改变 Url.Content 的行为,以便它使用网址 localhost / content / image.png生成我的图片网址

1 个答案:

答案 0 :(得分:2)

这可能不是最佳解决方案,但它可能适合您:

您可以编写如下所示的扩展程序来实现此目的:

    // 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;
    }

在Action中,您可以将静态IsUseLocalhost设置为true以使用localhost转换所有gen url。

然后在视图中使用它:

@Url.ContentFullPath("~/content/image.png")

如果要设置explicity主机,则在视图中将其用作:

@Url.ContentFullPath("~/content/image.png", host: "localhost")
相关问题