如何在ASP.NET Core MVC中显示绝对URL

问题描述 投票:0回答:1

如何才能获得在视图上显示的绝对URL?

我目前在我的代码中有这个:

<link href="~/css/site.min.css" rel="stylesheet" />

..which显示如下:

<link href="/css/site.min.css" rel="stylesheet" />

我要找的是以下内容:

<link href="http://www.example.com/css/site.min.css" rel="stylesheet" />

我知道你可以用更老的ASP.NET MVC 5做到这一点,但核心版本可能吗?

是否值得拥有绝对URL,或者相对URL是否足够?

asp.net asp.net-mvc razor asp.net-core
1个回答
2
投票

您应该自己构建URL。看看this answer,但我不认为你的情况需要一个绝对的网址。

以下是您将在该答案中找到的内容摘要:

public static string AbsoluteContent(this IUrlHelper url, string contentPath)
{
    HttpRequest request = url.ActionContext.HttpContext.Request;
    return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
}

使用该辅助方法,您将在视图中写入此内容,以获取位于site.css下的wwwroot的绝对URL:

@Url.AbsoluteContent("~/site.css")
© www.soinside.com 2019 - 2024. All rights reserved.