156

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?

tmg
  • 19,895
  • 5
  • 72
  • 76
oneNiceFriend
  • 6,691
  • 7
  • 29
  • 39
  • 2
    Like this? http://stackoverflow.com/questions/28120222/get-raw-url-from-microsoft-aspnet-http-httprequest – DavidG Jul 18 '16 at 12:48
  • 6
    @DavidG It appears that you can now use UriHelper.GetDisplayUrl(Re‌​quest) – Mark G Apr 28 '17 at 00:43

13 Answers13

181

You have to get the host and path separately.

 @Context.Request.Host
 @Context.Request.Path
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
Clint B
  • 4,610
  • 2
  • 18
  • 22
  • 28
    This will not report the correct url if you app is sitting in a virtual directory. You will need to prefix the **Request.Path** value with the **Request.PathBase** value if there is one. This applies to almost all the other answers to this question as well. – padigan Nov 20 '17 at 17:02
  • What is this `@` between the two strings? could you explain it? – Mohammed Noureldin Dec 25 '17 at 19:53
  • 3
    @MohammedNoureldin: that's razor view syntax. – jack.pop Jan 25 '18 at 08:16
  • 3
    For razor pages I had to use `@HttpContext` instead of `@Context`. For partial views `@Context` works. Did i forget an using? – Andriod Aug 03 '18 at 22:44
  • 3
    There is an easy way in MVC `Url.Action("Action", null, null, Request.Url.Scheme);` https://stackoverflow.com/questions/434604/how-do-i-find-the-absolute-url-of-an-action-in-asp-net-mvc – Dan Apr 03 '19 at 19:48
  • 2
    You'd need to add `Request.QueryString` to the end as Request.Path doesn't include the query string – Menol Oct 23 '19 at 11:45
  • `Url.Content("~/.....") ` it will translate to the home app path – Peyman Majidi Oct 19 '22 at 08:18
148

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}")
tmg
  • 19,895
  • 5
  • 72
  • 76
  • 1
    How do you get the fragment, say http://test.com/abc#123, how do you get the #123 fragment from the request? – Ray Oct 02 '17 at 17:19
  • 6
    @fanray You can't. Browsers are not sending URI-fragments to the server – tmg Oct 02 '17 at 17:46
  • Consider using [UriBuilder](https://learn.microsoft.com/en-us/dotnet/api/system.uribuilder?view=netcore-2.2) to build urls. – Erik Philips Jun 28 '19 at 20:28
123

You can use the extension method of Request:

Request.GetDisplayUrl()
AlexBar
  • 2,028
  • 1
  • 19
  • 13
  • 46
    This works if you add `@using Microsoft.AspNetCore.Http.Extensions` then `@Context.Request.GetDisplayUrl()` – Serj Sagan Sep 20 '17 at 00:35
  • 2
    still getting - Request does not exist in the current context – SeanMC Dec 27 '17 at 17:02
  • 2
    Keep in mind the intellisense summary for this function says `Suitable only for display. This format should not be used in HTTP headers or other HTTP operations.` Based on this, I think @tmg's solution is best (perhaps wrapped in your own extension method). – Gordon Glas Jul 31 '19 at 15:58
  • if you want it in the same type of Url object as it used to be you can do this once you have the display url: var uri = new Uri(displayUrl); – rdans Sep 21 '20 at 14:47
24

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.

mcNux
  • 1,472
  • 1
  • 15
  • 13
19

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.

Dhanuka777
  • 8,331
  • 7
  • 70
  • 126
  • 12
    Things like this make me think .Net Core is a step backwards in some ways. Is this better than Request.Url in Asp.Net in some way that I am unable to imagine? – Soenhay Feb 21 '18 at 19:30
11

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
Sam Alekseev
  • 2,281
  • 2
  • 19
  • 28
11

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.

Emran Hussain
  • 11,551
  • 5
  • 41
  • 48
9

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.

Christopher King
  • 1,691
  • 23
  • 28
8
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);
}
Sergey
  • 240
  • 3
  • 4
  • but where are you getting `httpContext` ? That is not going to work with `Microsoft.AspNetCore.Http.HttpContext.Request` – Tom Stickel Feb 04 '19 at 23:07
8

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).

Hallmanac
  • 529
  • 2
  • 8
  • 14
3
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";
Husam Ebish
  • 4,893
  • 2
  • 22
  • 38
1

You may want to get the URL to use it on the razor side, there is an alternative way to get the home app URL:

Url.Content("~/.....")

Example

In the following example, I wanted to generate a QR code and display it in an img tag src, because of using custom route annotation in the Action, I can't use @URL.Action so as an alternative solution I use ~ like this:

<script>
    $("#imgCode").attr("src", "@(Url.Content("~/generateQr/"))"+ code);

</script>

Controller Side

[Route("/generateQr/{code}")]
...
Peyman Majidi
  • 1,777
  • 2
  • 18
  • 31
0

ILSpy show how it was done in Microsoft.Owin.dll.

// Microsoft.Owin.OwinRequest
using System;

/// <summary>
/// Gets the uniform resource identifier (URI) associated with the request.
/// </summary>
/// <returns>The uniform resource identifier (URI) associated with the request.</returns>
public virtual Uri Uri => new Uri(string.Concat(Scheme, Uri.SchemeDelimiter, Host, PathBase, Path, QueryString));

I wonder why they removed this property.

osexpert
  • 485
  • 1
  • 6
  • 18