本文介绍了MVC 6 IUrlHelper依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过依赖注入使用IUrlHelper,以便能够使用其功能为不同的其他终结点生成uri.我似乎无法弄清楚如何从头开始创建UrlHelper,因为它在MVC 6中已更改,并且MVC不会在IoC控制器中自动提供该服务.

I want to use IUrlHelper through dependency injection to be able to use its functionality to generate uris for different rest endpoints. I cant seem how to figure out how to create a UrlHelper from scratch because it changed in MVC 6 and MVC doesnt automatically have that service available in the IoC controller.

设置是我的控制器将内部模型转换为api模型转换器类,并且使用IUrlHelper(全部通过Depenedency Injection).

The setup is my Controller take in an internal model to api model converter class and that uses the IUrlHelper (all through Depenedency Injection).

如果可以使用IUrlHelper/UrlHelper更好的替代方法,那么我可以为我的WebApi操作/控制器生成Uris.

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

推荐答案

该方法现在已过时.查看下面的更新.

代替services.AddTransient<IUrlHelper, UrlHelper>()或尝试直接注入IUrlHelper,您可以注入IHttpContextAccessor并从那里获取服务.

Instead of services.AddTransient<IUrlHelper, UrlHelper>() or trying to directly inject IUrlHelper you can inject IHttpContextAccessor and get the service from there.

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

除非只是一个错误,否则将UrlHelper服务与IUrlHelper服务一起添加是行不通的.

Unless it is just a bug, adding the IUrlHelper service with UrlHelper does not work.

更新2017-08-28

以前的方法似乎不再起作用.下面是一个新的解决方案.

The previous method no longer seems to work.Below is a new solution.

将IActionContextAccessor配置为服务:

Confgure IActionContextAccessor as a service:

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

然后注入IActionContextAccessor和IUrlHelperFactory,然后生成如下所示的IUrlHelper

Then inject IActionContextAccessor and IUrlHelperFactory to then generate the IUrlHelper like below

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();
    }
}

这篇关于MVC 6 IUrlHelper依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:47