Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
like image 398
BlackHoleGalaxy Avatar asked Jan 06 '17 18:01

BlackHoleGalaxy


People also ask

What is URL RouteUrl?

RouteUrl(String, Object) Generates a fully qualified URL for the specified route values by using a route name. RouteUrl(String, RouteValueDictionary) Generates a fully qualified URL for the specified route values by using a route name.

What is attribute routing in C#?

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

What is MapRoute in MVC?

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.

What is ApiController attribute?

The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.


1 Answers

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

like image 109
Balaji Marimuthu Avatar answered Sep 27 '22 21:09

Balaji Marimuthu