Getting current URL on the browser in ASP.NET 6

JORGE MALDONADO BARRERA 211 Reputation points
2022-07-14T16:53:07.397+00:00

Hi,

I am developing an ASP.NET 6 website and I am decomposing the current URL on the browser. To get the current URL I am using the following C# instruction:

Uri address = new Uri(Request.Host.ToString());  

I see that Request is a method of ControllerBase and the result is of type HttpRequest. Watching Microsoft documentation, it seems to me that this was designed for .NET Framework 4.8 (and below) but I am not sure.

Doing a bit more of research, I found the HttpWebRequest class that might do the job of what I need but Microsoft documentation says this is not recommended for new development and that System.Net.Http.HttpClient should be considered but after going over the HttpClient documentation I do not see how to get the current URL in the browser.

I will very much appreciate your feedback on my issue so I can get the current URL on the browser in the best possible way.

Respectfully,
Jorge Maldonado

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,216 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 1,916 Reputation points
    2022-07-15T00:50:46.483+00:00

    According to the Microsoft documents;

    The HttpRequest represents the incoming side of an individual HTTP request.

    The HttpWebRequest provides an HTTP-specific implementation of the WebRequest class which makes a request to a Uniform Resource Identifier (URI).

    They are far different. You have to use the HttpRequest for "Getting current URL on the browser in ASP.NET 6."

    1 person found this answer helpful.
    0 comments No comments

  2. Qing Guo - MSFT 886 Reputation points Microsoft Vendor
    2022-07-15T02:17:43.5+00:00

    Hi @JORGE MALDONADO BARRERA ,

    This document is for .NET Framework 4.8 (and below).
    Please see the new document , HttpRequest applies to ASP.NET 6.

    Below is an example:

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

    result:

    220947-2.png

    ----------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Qing Guo

    0 comments No comments