ChatGPT解决这个技术问题 Extra ChatGPT

Get raw URL from Microsoft.AspNetCore.Http.HttpRequest

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?

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
@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.
did you try ToString() ?

M
Matt DeKrey

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!


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()".
L
Leo Hendry

Add the Nuget package / using:

using Microsoft.AspNetCore.Http.Extensions; 

(In ASP.NET Core RC1 this was in Microsoft.AspNet.Http.Extensions)

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.


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.
k
khellang

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.


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
S
Shadi Alnamrouti

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

g
giammin

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;
}

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

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;
}

U
Uwe Keim

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}";
    }
}

S
Smartkid

In ASP.NET 5 beta5:

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