Brendan Vogt
Brendan Vogt

Reputation: 26058

How to display the absolute url in ASP.NET Core MVC

How would I be able to get the absolute URL to display on a view?

I currently have this in my code:

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

..which displays like this:

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

What I am looking for is the following:

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

I know you could do it with the older ASP.NET MVC 5, but is this possible with the core versions?

Is it worthwhile having an absolute URL, or will a relative URL be sufficient?

Upvotes: 0

Views: 2784

Answers (1)

Ashkan Nourzadeh
Ashkan Nourzadeh

Reputation: 1942

You should construct the URL yourself. take a look at this answer, but I don't think an absolute url is required in your case.

Here is a summary of what you will find in that 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();
}

with that helper method, you will write this in your view to get the absolute URL to site.css located under wwwroot:

@Url.AbsoluteContent("~/site.css")

Upvotes: 5

Related Questions