Get the full route to current action

37,965

Solution 1

You can get the complete requested url using the Request option (HttpRequest) in .Net Core.

var route = Request.Path.Value;

Your final code.

[Route("api/[controller]")]
public class DocumentController : Controller
{
    [HttpGet("info/{Id}")]
    public async Task<Data> Get(string Id)
    {
        var route = Request.Path.Value;
    }
}

Result route: "/api/document/info/some-id-here" //for example

Solution 2

You can also ask MVC to create a new route URL based on the current route values:

[Route("api/[controller]")]
public class DocumentController : Controller
{
    [HttpGet("info/{Id}")]
    public async Task<Data> Get(string Id)
    {
        //Logic

        var myRoute = Url.RouteUrl(RouteData.Values);
    }
}

Url.RouteUrl is a helper method that lets you build a route URL given any route values. RouteData.Values gives you the route values for the current request.

Solution 3

If you want the original route template on an API controller that was specified with any HttpMethod attribute then this will do it:

var routeAttribute = Url.ActionContext.ActionDescriptor.EndpointMetadata.First(d => d is HttpMethodAttribute);
var routeTemplate = ((HttpMethodAttribute)routeAttribute).Template;

If the original route attribute was: [HttpGet("Self/{id}")]

The routeTemplate value would be: "Self/{id}"

Share:
37,965
BlackHoleGalaxy
Author by

BlackHoleGalaxy

Updated on August 07, 2022

Comments

  • BlackHoleGalaxy
    BlackHoleGalaxy over 1 year

    I have a simple API with basic routing. It was setup using the default Visual Studio 2015 ASP.NET Core API template.

    I have this controller and action:

    [Route("api/[controller]")]
    public class DocumentController : Controller
    {
        [HttpGet("info/{Id}")]
        public async Task<Data> Get(string Id)
        {
            //Logic
        }
    }
    

    So to reach this method, I must call GET /api/document/info/some-id-here.

    Is it possible with .NET Core, inside that method, to retrieve as a string the complete route?

    So I could do for example:

    var myRoute = retrieveRoute();
    
    // myRoute = "/api/document/info/some-id-here"