Arun Selva Kumar
Arun Selva Kumar

Reputation: 2732

How to I get the WebAPI Route Url using the Route Name

The question is quiet naive, but I couldn't find the solution online or in Microsoft's docs (or I may not be looking enough :-))

So here, I have a method marked with attribute of HttpGet with a route name "GetValues". Is there a way to get the Url of the route using the route name (which I believe is the sole point of having route name).

    [Route("api/Values")]
    public class ValuesController : ControllerBase
    {
        [HttpGet("{id}", Name = "GetValues")]
        public async Task<IActionResult> GetValuesAsync()
        {

        }
}

Upvotes: 0

Views: 84

Answers (1)

SLDev
SLDev

Reputation: 336

The simple solution is:

var url = Url.Link("GetValues", "Values", new { id = 123 });

But the complete url is:

var url = string.Format("{0}{1}", 
                        Request.Url.Authority,
                        Url.Action("GetValues", "Values", new { id = 123 }));

Upvotes: 2

Related Questions