BlackHoleGalaxy
BlackHoleGalaxy

Reputation: 9662

Get the full route to current action

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"

Upvotes: 42

Views: 65517

Answers (4)

Егор Егоров
Егор Егоров

Reputation: 27

Url.ActionContext.ActionDescriptor.AttributeRouteInfo.Template

"v{version}/{cardId}/cardsTest" {$1}

Upvotes: 0

N-ate
N-ate

Reputation: 6926

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

Upvotes: 3

Nate Barbettini
Nate Barbettini

Reputation: 53600

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.

Upvotes: 12

Balaji Marimuthu
Balaji Marimuthu

Reputation: 2058

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

Upvotes: 57

Related Questions