Get raw URL from Microsoft.AspNetCore.Http.HttpRequest
Asked Answered
D

10

152

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?

Dardanelles answered 23/1, 2015 at 23:9 Comment(3)
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/110Jaala
@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.Dardanelles
did you try ToString() ?Aramenta
M
122

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!

Maleate answered 16/4, 2015 at 2:49 Comment(6)
This no longer works as of beta-5. I do not have a good alternative or would update my answer.Maleate
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.Doublestop
using Microsoft.AspNet.Http.Extensions; and that Request.GetDisplayUrl()Negrophobe
The right namespace is now Microsoft.AspNetCore.Http.ExtensionsBawdyhouse
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()".Raab
For Azure Functions: add reference #r "Microsoft.AspNetCore.Http.Extensions", add using Microsoft.AspNet.Http.Extensions; and use like UriHelper.GetDisplayUrl(req) or UriHelper.GetEncodedUrl(req) as required.Zany
A
131

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.

Arenaceous answered 15/3, 2016 at 19:23 Comment(7)
Is ASP.NET Core RC2 available now?Tatianatatianas
Yes - blogs.msdn.microsoft.com/webdev/2016/05/16/…Arenaceous
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 -> /.Flooded
NO NO - This will not work. NEITHER GetEncodedUrl() nor GetDisplayUrl() are available methods anymore.Exemplificative
@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.Beilul
@NickMertin - I'm not in front of my Core application so I can't tell you which type of application, but I will say that there are so many times that things are abstracted in an existing application that doing a migration - I didn't have the ability to even include certain namespaces. Example: you simply cannot get all the same namespaces in a class library core project that you can get in a mvc core application project. I know this reply is vague - but I end up writing a lot of middleware to get around the changes presented in .net core - also .net core 2.2 has changed from 2.1 etc..Exemplificative
@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.Beilul
M
122

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!

Maleate answered 16/4, 2015 at 2:49 Comment(6)
This no longer works as of beta-5. I do not have a good alternative or would update my answer.Maleate
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.Doublestop
using Microsoft.AspNet.Http.Extensions; and that Request.GetDisplayUrl()Negrophobe
The right namespace is now Microsoft.AspNetCore.Http.ExtensionsBawdyhouse
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()".Raab
For Azure Functions: add reference #r "Microsoft.AspNetCore.Http.Extensions", add using Microsoft.AspNet.Http.Extensions; and use like UriHelper.GetDisplayUrl(req) or UriHelper.GetEncodedUrl(req) as required.Zany
B
38

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.

Blais answered 3/8, 2016 at 15:20 Comment(5)
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?Auerbach
RawTarget was added in the 1.0 release, back in may. Are you sure you're running on the latest version?Blais
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 /.Flooded
This is by far the authoritative answer.Pesade
This appears to give the URL Path rather than the entire URLPeeved
K
26

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
Koosis answered 21/2, 2019 at 9:57 Comment(0)
A
20

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;
}
Audition answered 16/4, 2018 at 10:47 Comment(4)
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.Superstitious
@user3172616 nice idea!Audition
(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).Byrdie
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 :)Fortunetelling
S
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;
}
Shiff answered 1/7, 2015 at 8:45 Comment(0)
R
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}";
    }
}
Rundell answered 3/11, 2016 at 8:37 Comment(0)
T
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, "");
Traps answered 20/9, 2022 at 12:29 Comment(1)
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.Trichromatism
C
0

In ASP.NET 5 beta5:

Microsoft.AspNet.Http.Extensions.UriHelper.Encode(
    request.Scheme, request.Host, request.PathBase, request.Path, request.QueryString);
Cardoso answered 19/7, 2015 at 4:24 Comment(0)
C
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.

Channa answered 25/11, 2023 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.