Search code examples
c#asp.net-corerequestroutevalues

How to get the current url with route values?


I'm trying to retrieve the current request url with routes values, in order to have a return url with all needed values when reaching my controllers.

I tried HttpContext.Request.Path and HttpContext.Request.GetDisplayUrl() but it returns something like :

/Home/Products

What I actually need is to retrive the routes values to have :

/Home/Products?id=1

Is there a way to achieve that? Thanks !


Solution

  • You can do this

    HttpContext.Request.Path + HttpContext.Request.QueryString
    

    Or for convenience you can create an extension method like this

    public static string GetCurrentUrl(this HttpRequest httpRequest)
    {
        return httpRequest.Path + httpRequest.QueryString;
    }
    

    Then get current URL

    var url = HttpContext.Request.GetCurrentUrl();
    

    This link maybe helpful for you.