How to get current url in view in asp.net core 1.0

asp.net Coreasp.net Core-Mvcasp.net Core-1.0

asp.net Core Problem Overview


In previous versions of asp.net, we could use

@Request.Url.AbsoluteUri

But it seems it's changed. How can we do that in asp.net core 1.0?

asp.net Core Solutions


Solution 1 - asp.net Core

You have to get the host and path separately.

 @Context.Request.Host
 @Context.Request.Path

Solution 2 - asp.net Core

You need scheme, host, path and queryString

@string.Format("{0}://{1}{2}{3}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path, Context.Request.QueryString)

or using new C#6 feature "String interpolation"

@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")

Solution 3 - asp.net Core

You can use the extension method of Request:

Request.GetDisplayUrl()

Solution 4 - asp.net Core

This was apparently always possible in .net core 1.0 with Microsoft.AspNetCore.Http.Extensions, which adds extension to HttpRequest to get full URL; GetEncodedUrl.

e.g. from razor view:

@using Microsoft.AspNetCore.Http.Extensions
...
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>

Since 2.0, also have relative path and query GetEncodedPathAndQuery.

Solution 5 - asp.net Core

Use the AbsoluteUri property of the Uri, with .Net core you have to build the Uri from request like this,

 var location = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}");
            
 var url = location.AbsoluteUri;

e.g. if the request url is 'http://www.contoso.com/catalog/shownew.htm?date=today'; this will return the same url.

Solution 6 - asp.net Core

You can consider to use this extension method (from Microsoft.AspNetCore.Http.Extensions namespace:

@Context.Request.GetDisplayUrl()

For some my projects i prefer more flexible solution. There are two extensions methods.

  1. First method creates Uri object from incoming request data (with some variants through optional parameters).

  2. Second method receives Uri object and returns string in following format (with no trailing slash): Scheme_Host_Port

    public static Uri GetUri(this HttpRequest request, bool addPath = true, bool addQuery = true) { var uriBuilder = new UriBuilder { Scheme = request.Scheme, Host = request.Host.Host, Port = request.Host.Port.GetValueOrDefault(80), Path = addPath ? request.Path.ToString() : default(string), Query = addQuery ? request.QueryString.ToString() : default(string) }; return uriBuilder.Uri; }

     public static string HostWithNoSlash(this Uri uri)
     {
         return uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
     }
    

Usage:

//before >> https://localhost:44304/information/about?param1=a&param2=b
        Request.GetUri(addQuery: false);
        //after >> https://localhost:44304/information/about

        //before >> https://localhost:44304/information/about?param1=a&param2=b
        new Uri("https://localhost:44304/information/about?param1=a&param2=b").GetHostWithNoSlash();
        //after >> https://localhost:44304

Solution 7 - asp.net Core

The accepted answer helped me, as did the comment for it from @padigan but if you want to include the query-string parameters as was the case for me then try this:

@Context.Request.PathBase@Context.Request.GetEncodedPathAndQuery()

And you will need to add @using Microsoft.AspNetCore.Http.Extensions in the view in order for the GetEncodedPathAndQuery() method to be available.

Solution 8 - asp.net Core

If you're looking to also get the port number out of the request you'll need to access it through the Request.Host property for AspNet Core.

The Request.Host property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"), then calling Request.Host will give you the host domain and the port number like so: "example.com:8080".

If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host or Request.Host.Port).

Solution 9 - asp.net Core

There is a clean way to get the current URL from a Razor page or PageModel class. That is:

Url.PageLink()

Please note that I meant, the "ASP.NET Core Razor Pages", not the MVC.

I use this method when I want to print the canonical URL meta tag in the ASP.NET Core razor pages. But there is a catch. It will give you the URL which is supposed to be the right URL for that page. Let me explain.

Say, you have defined a route named "id" for your page and therefore, your URL should look like

> http://example.com/product?id=34

The Url.PageLink() will give you exactly that URL as shown above.

Now, if the user adds anything extra on that URL, say,

> http://example.com/product?id=34&somethingElse

Then, you will not get that "somethingElse" from this method. And that is why it is exactly good for printing canonical URL meta tag in the HTML page.

Solution 10 - asp.net Core

public string BuildAbsolute(PathString path, QueryString query = default(QueryString), FragmentString fragment = default(FragmentString))
{
	var rq = httpContext.Request;
	return Microsoft.AspNetCore.Http.Extensions.UriHelper.BuildAbsolute(rq.Scheme, rq.Host, rq.PathBase, path, query, fragment);
}

Solution 11 - asp.net Core

var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiononeNiceFriendView Question on Stackoverflow
Solution 1 - asp.net CoreClint BView Answer on Stackoverflow
Solution 2 - asp.net CoretmgView Answer on Stackoverflow
Solution 3 - asp.net CoreAlexBarView Answer on Stackoverflow
Solution 4 - asp.net CoremcNuxView Answer on Stackoverflow
Solution 5 - asp.net CoreDhanuka777View Answer on Stackoverflow
Solution 6 - asp.net CoreSam AlekseevView Answer on Stackoverflow
Solution 7 - asp.net CoreChristopher KingView Answer on Stackoverflow
Solution 8 - asp.net CoreHallmanacView Answer on Stackoverflow
Solution 9 - asp.net CoreEmran HussainView Answer on Stackoverflow
Solution 10 - asp.net CoreSergeyView Answer on Stackoverflow
Solution 11 - asp.net CoreHusam EbishView Answer on Stackoverflow