You really shouldn’t create a UrlHelper
yourself. It’s likely that whatever context you are currently in, there is already an IUrlHelper
instance available:
So chances are, that you can just access this.Url
to get an URL helper.
If you find yourself in a situation where that does not exist, for example when implementing your own service, then you can always inject a IUrlHelperFactory
together with the IActionContextAccessor
to first retrieve the current action context and then create an URL helper for it.
As for what that ActionContext
is, it is basically an object that contains various values that identify the current MVC action context in which the current request is being handled. So it contains information about the actual request, the resolved controller and action, or the model state about the bound model object. It is basically an extension to the HttpContext
, also containing MVC-specific information.
If you are running ASP.NET Core 2.2 or later, you can also use the LinkGenerator
instead of the IUrlHelper
inside your services which gives you an easier way to generate URLs compared to having to construct the helper through the IUrlHelperFactory
.