159

The HttpRequest class in Asp.Net 5 (vNext) contains (amongst other things) parsed details about the URL for the request, such as Scheme, Host, Path etc.

I've haven't spotted anywhere yet that exposes the original request URL though - only these parsed values. (In previous versions there was Request.Uri)

Can I get the raw URL back without having to piece it together from the components available on HttpRequest?

3
  • 1
    A bug seems to have been filed earlier about this but closed...you can probably check the details of it and if you feel stronger about it, may be update it with details: github.com/aspnet/HttpAbstractions/issues/110 Commented Jan 24, 2015 at 19:30
  • @KiranChalla: I sort of take their point, although it does lead me to wonder what the RawURL is in previous versions then. I guess what they are currently showing about the scheme, host etc can be divined from the server side handling of the request, and not anything on the request itself. Commented Jan 24, 2015 at 22:05
  • did you try ToString() ? Commented Feb 25, 2015 at 16:27

10 Answers 10

138

Add the using:

using Microsoft.AspNetCore.Http.Extensions; 

(In previous versions of the ASP.NET Core framework this required a NuGet package, either Microsoft.AspNet.Http.Extensions or Microsoft.AspNetCore.Http.Extensions, but now comes with the framework.)

then you can get the full http request url by executing:

var url = httpContext.Request.GetEncodedUrl();

or

var url = httpContext.Request.GetDisplayUrl();

depending on the purposes.

Sign up to request clarification or add additional context in comments.

7 Comments

Is ASP.NET Core RC2 available now?
Looking at source, these clearly do some encoding/decoding so this will not be the raw url. Also, IIS will change sometimes change the url before it gets to Kestrel e.g. %2F -> /.
@TomStickel Not sure what you're talking about... I had no issue using either of them. Make sure you have the using directive in you file as described in the answer, as these are not "normal" methods, but rather extension methods.
@TomStickel fair. Just noting that with the Microsoft.AspNetCore.All package installed for ASP.NET Core 2.2 (also tested on 2.0), this works fine for me.
|
123

It looks like you can't access it directly, but you can build it using the framework:

Microsoft.AspNetCore.Http.Extensions.UriHelper.GetFullUrl(Request)

You can also use the above as an extension method.

This returns a string rather than a Uri, but it should serve the purpose! (This also seems to serve the role of the UriBuilder, too.)

Thanks to @mswietlicki for pointing out that it's just been refactored rather than missing! And also to @C-F to point out the namespace change in my answer!

6 Comments

This no longer works as of beta-5. I do not have a good alternative or would update my answer.
I believe this was made a true extension method - you simply import the namespace and call either GetEncodedUri or GetDisplayUri, depending on your use case.
using Microsoft.AspNet.Http.Extensions; and that Request.GetDisplayUrl()
The right namespace is now Microsoft.AspNetCore.Http.Extensions
For ASP.NET Core 1.0 add the using "Microsoft.AspNetCore.Http.Extensions" to your Razor view. To get the url use "@Context.Request.GetDisplayUrl()".
|
40

If you really want the actual, raw URL, you could use the following extension method:

public static class HttpRequestExtensions
{
    public static Uri GetRawUrl(this HttpRequest request)
    {
        var httpContext = request.HttpContext;

        var requestFeature = httpContext.Features.Get<IHttpRequestFeature>();

        return new Uri(requestFeature.RawTarget);
    }
}

This method utilizes the RawTarget of the request, which isn't surfaced on the HttpRequest object itself. This property was added in the 1.0.0 release of ASP.NET Core. Make sure you're running that or a newer version.

NOTE! This property exposes the raw URL, so it hasn't been decoded, as noted by the documentation:

This property is not used internally for routing or authorization decisions. It has not been UrlDecoded and care should be taken in its use.

5 Comments

I'm using ASP .NET Core with full .NET Framework. This doesn't seem to work for me (RawTarget is not defined on IHttpRequestFeature). Can you think of an alternative?
RawTarget was added in the 1.0 release, back in may. Are you sure you're running on the latest version?
If hosting using IIS, IIS will change sometimes change the url before it gets to Kestrel. One Example of this is %2F gets decoded to /.
This is by far the authoritative answer.
This appears to give the URL Path rather than the entire URL
27

In .NET Core razor:

@using Microsoft.AspNetCore.Http.Extensions
@Context.Request.GetEncodedUrl() //Use for any purpose (encoded for safe automation)

You can also use instead of the second line:

@Context.Request.GetDisplayUrl() //Use to display the URL only

Comments

22

The other solutions did not fit well my needs because I wanted directly an URI object and I think it is better to avoid string concatenation (also) in this case so I created this extension methods than use a UriBuilder and works also with urls like http://localhost:2050:

public static Uri GetUri(this HttpRequest request)
{
    var uriBuilder = new UriBuilder
    {
        Scheme = request.Scheme,
        Host = request.Host.Host,
        Port = request.Host.Port.GetValueOrDefault(80),
        Path = request.Path.ToString(),
        Query = request.QueryString.ToString()
    };
    return uriBuilder.Uri;
}

4 Comments

Good one. Also i improved your solution with optional parameters. Therefore i can control which part of URI i want to retreive. For example, host only or full path without query string etc.
@user3172616 nice idea!
(80) should be (-1). When you have https scheme with port omitted in the "Host" header this will generate wrong Uri (e.g. https://myweb:80/, with (-1) it will be https://myweb).
using request.Host.Value would be better, and you're missing request.PathBase if the app uses a PathBase. Also, it would be better to use .Value for the QueryString :)
5

The following extension method reproduces the logic from the pre-beta5 UriHelper:

public static string RawUrl(this HttpRequest request) {
    if (string.IsNullOrEmpty(request.Scheme)) {
        throw new InvalidOperationException("Missing Scheme");
    }
    if (!request.Host.HasValue) {
        throw new InvalidOperationException("Missing Host");
    }
    string path = (request.PathBase.HasValue || request.Path.HasValue) ? (request.PathBase + request.Path).ToString() : "/";
    return request.Scheme + "://" + request.Host + path + request.QueryString;
}

Comments

5

This extension works for me:

using Microsoft.AspNetCore.Http;

public static class HttpRequestExtensions
{
    public static string GetRawUrl(this HttpRequest request)
    {
        var httpContext = request.HttpContext;
        return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.Path}{httpContext.Request.QueryString}";
    }
}

Comments

1

For me the best way to retrieve the base URL on .NET Core 6

using Microsoft.AspNetCore.Http.Extensions;

var url = request.GetDisplayUrl();
var path = request.Path.ToString();
                      
string baseUrl = url.Replace(path, "");

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

In ASP.NET 5 beta5:

Microsoft.AspNet.Http.Extensions.UriHelper.Encode(
    request.Scheme, request.Host, request.PathBase, request.Path, request.QueryString);

Comments

0

I have created a page to see the actual values that you get from the Request object. You can change the ending part of the URL to anything.

https://developer.azurewebsites.net/aspnet-core-request-property-values#extensionmethods shows that you get the whole URL via extensionmethods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.