MVC 6 IUrlHelper Injection Dependency Injection

I want to use IUrlHelper through dependency injection to be able to use its functions to generate uris for different rest endpoints. I cannot figure out how to create UrlHelper from scratch because it has changed in MVC 6, and MVC does not automatically have this service available in the IoC controller.

Customization - my controller accepts an internal model for the api model converter class and uses IUrlHelper (via Injection Dependency Injection).

If there is a better alternative to IUrlHelper / UrlHelper, I can use Uris for my action / WebApi controllers to generate. I am open to suggestions.

+9
source share
4 answers

. .

services.AddTransient<IUrlHelper, UrlHelper>() IUrlHelper IHttpContextAccessor .

public ClassConstructor(IHttpContextAccessor contextAccessor)
{
    this.urlHelper = contextAccessor.HttpContext.RequestServices.GetRequiredService<IUrlHelper>();
}

, IUrlHelper UrlHelper .

2017-08-28

. .

IActionContextAccessor :

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
        .AddMvc();
}

IActionContextAccessor IUrlHelperFactory, IUrlHelper,

public class MainController : Controller
{
    private IUrlHelperFactory urlHelperFactory { get; }
    private IActionContextAccessor accessor { get; }
    public MainController(IUrlHelperFactory urlHelper, IActionContextAccessor accessor)
    {
        this.urlHelperFactory = urlHelper;
        this.accessor = accessor;
    }

    [HttpGet]
    public IActionResult Index()
    {
        ActionContext context = this.accessor.ActionContext;
        IUrlHelper urlHelper = this.urlHelperFactory.GetUrlHelper(context);
        //Use urlHelper here
        return this.Ok();
    }
}
+7

UrlHelper , ActionContextAccessor. :

        services.AddScoped<IActionContextAccessor, ActionContextAccessor>();
        services.AddScoped<IUrlHelper>(x =>
        {
            var  actionContext = x.GetService<IActionContextAccessor>().ActionContext;
            return new UrlHelper(actionContext);
        });

IUrlHelper , , IHttpContextAccessor.

+10

ASP.NET Core 2.0

PM> Install-Package AspNetCore.IServiceCollection.AddIUrlHelper

public void ConfigureServices(IServiceCollection services)
{
   ... 
   services.AddUrlHelper();
   ... 
}

:

+1

For ASP.Net Core 2.0, you do not have to enter IUrlHelper. Available as a controller property. ControllerBase.Url is an instance of IUrlHelper.

0
source

All Articles