Get the full route to the current action.

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

I have this controller and action:

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

To achieve this method, I have to call GET /api/document/info/some-id-here .

Is it possible using .NET Core, inside this method, to get the full route as a string?

Therefore, I could do, for example:

 var myRoute = retrieveRoute(); // myRoute = "/api/document/info/some-id-here" 
+7
c # asp.net-core asp.net-core-mvc .net-core
source share
2 answers

You can get the full requested URL using the Request (HttpRequest) option in .Net Core.

 var route = Request.Path.Value; 

Your last code.

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

The result of the route: "/ api / document / info / some-id-here" // for example

+11
source share

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 allows you to build a route URL based on any route values. RouteData.Values gives you the route values โ€‹โ€‹for the current request.

+4
source share

All Articles