I needed to generate a URL that I could return inside an ASP.NET Controller.
Thanks to the built-in UrlHelper that is something that even I can do. At least that was what I thought…
This is the code I tried:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var link = Url.Action( | |
nameof(ProductController.Get), | |
nameof(ProductController), | |
new { id = Id }); |
Surprisingly this didn’t work. It turns out that the controller argument needs the controllername without the controller suffix. So in my example above ProductController should be Product instead.
I changed it to this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var controllerName = nameof(ProductController); | |
var controller = controllerName.Remove( | |
controllerName.LastIndexOf( | |
"Controller", | |
StringComparison.Ordinal)); | |
var link = Url.Action( | |
nameof(ProductController.Get), | |
controller, | |
new { id = Id }); |
Still refactor friendly but unfortunately a lot less readible.