4

I need to get the absolute URL of a few actions in ASP.NET core 1.0.1:

public IActionResult Test(IUrlHelper urlHelper) {
  var url = urlHelper.Action(nameof(HomeController.Index), Request.Scheme)
  return Ok(url);
}

Or

public IActionResult Test(IUrlHelper urlHelper) {
  var url = urlHelper.RouteUrl(nameof(HomeController.Index), Request.Scheme)
  return Ok(url);
}

None of this gave me the Absolute Url of the home route.

How can I do this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • I am not quite sure if it's possible to achieve, but theoretically there can be multiple routes mapped to your action e.g. How do you plan to get absolute URL if multiple routes can lead to the same action? – Ilya Chernomordik Oct 23 '16 at 19:21
  • Sorry, I don't understand what you mean. I am just trying to get the Absolute Route ... I posted to examples of what I tried to accomplish the same thing but no success – Miguel Moura Oct 23 '16 at 19:24
  • If I understood your question correctly you have an action on controller (e.g. HomeController.Index) and you want to get a url by these names (e.g. www.myapp.com/home/index)? If such there can be multiple mappings (i.e. many urls that lead to the same route) and the only way to read them is probably from the router. – Ilya Chernomordik Oct 23 '16 at 19:30
  • Yes. That is what i need – Miguel Moura Oct 23 '16 at 19:51

2 Answers2

2

I have tried multiple solutions but none of them is giving the desired output, I am on Core 2.2.

Check this answer by Muhammad Rehan Saeed where he created a helper extension to implement this functionality. (answered June 2016 for Core 1.0 RC and onward and it is still working)

His answer has been revised by Josiah (in Nov 2017, in the same Question) in which instead of created a new Helper, he extended an existing .NET Core MVC Class so that the desired functionality appears to be a native solution:

Url.AbsoluteAction(...)
Url.AbsoluteContent(...)
Url.AbsoluteRouteUrl(...)

The code is well documented and easy to use. Hope it will be helpful for the folks who are lost in the solution of this apparently simple task.

BiLaL
  • 708
  • 11
  • 18
1

First get relative url, then get absolute url and use Url class constructor with two urls. Here is an accepted answer to similar question for ASP.NET MVC6, note that MVC6 became ASP.NET Core later on.

Community
  • 1
  • 1
Pawel Troka
  • 853
  • 2
  • 12
  • 33