在ASP.NET核心中注入IUrlHelper
在RC1中 , IUrlHelper
可以在服务中注入services.AddMvc()
在启动类中使用services.AddMvc()
)
这在RC2中不再起作用。 有没有人知道如何在RC2中做到这一点,因为刚刚新建一个UrlHelper
需要一个ActionContext
对象。 不知道如何在控制器之外得到它。
对于ASP.NET Core RC2 ,github repo上存在此问题 。 而不是注入IUrlHelper
,取一个IUrlHelperFactory
。 听起来你需要注入IActionContextAccessor
因为Controller
不再具有公共属性ActionContext
。
注册依赖项:
services.AddSingleton();
然后依靠它:
public SomeService(IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor) { var urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext); }
然后根据需要使用它。
对于Net Core 2.0
在service.AddMvc()
之后添加此项
services.AddSingleton(); services.AddScoped(factory => { var actionContext = factory.GetService() .ActionContext; return new UrlHelper(actionContext); });
ASP.NET Core 2.0
安装
PM> Install-Package AspNetCore.IServiceCollection.AddIUrlHelper
使用
public void ConfigureServices(IServiceCollection services) { ... services.AddUrlHelper(); ... }
免责声明:此套餐的作者
对于.Net Core 2.0
services.AddMvc(); services.AddScoped(x => { var actionContext = x.GetRequiredService().ActionContext; var factory = x.GetRequiredService(); return factory.GetUrlHelper(actionContext); });