Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core UrlHelper and how it works

I'm rather new to ASP.NET Core, and right now I am trying to get a grasp on how UrlHelper works in general.

In my controller, I want to create an absolute URL to another action in the same controller, e.g. http://localhost:PORT/api/controller/action. The question is now, how do I do it?

I have tried with the following:

var urlHelper = new UrlHelper(new ActionContext());
var url = urlHelper.Action("ACTION", "CONTROLLER");

Furthermore, what are those different contexts like ActionContext?

like image 312
Frederik Avatar asked Sep 27 '18 12:09

Frederik


People also ask

How do you use UrlHelper?

to call UrlHelper methods you just create a new instance, passing it a RequestContext to the constructor. I am not using this on a View. I am using it in a Model Validator Class. The class is also in the MVC project.

How does ASP.NET Core works?

An ASP.NET Core app uses an HTTP server implementation to listen for HTTP requests. The server surfaces requests to the app as a set of request features composed into an HttpContext . ASP.NET Core provides the following server implementations: Kestrel is a cross-platform web server.

What is the difference between .NET Core and ASP.NET Core?

NET Core is a runtime. It can execute applications that are built for it. ASP.NET Core is a collection of libraries that form a Framework for building web applications.


Video Answer


1 Answers

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:

  • ControllerBase.Url inside of controllers.
  • PageModel.Url inside a Razor view.
  • ViewComponent.Url inside a view component.

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.

like image 140
poke Avatar answered Oct 11 '22 18:10

poke