在ASP.NET核心中注入IUrlHelper

时间:2016-05-19 11:38:34

标签: c# asp.net-core asp.net-core-mvc asp.net-core-1.0

RC1 中,IUrlHelper可以在服务中注入(在启动类中使用services.AddMvc()

这在 RC2 中不再有效。是否有人知道如何在 RC2 中执行此操作,因为只需新增UrlHelper需要ActionContext个对象。不知道如何在控制器之外得到它。

6 个答案:

答案 0 :(得分:34)

对于 ASP.NET Core RC2 ,有一个issue for this on the github repo。不要注入IUrlHelper,而是IUrlHelperFactory。听起来您需要IActionContextAccessor注入Controller不再拥有公共财产ActionContext

注册依赖项:

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

然后依靠它:

public SomeService(IUrlHelperFactory urlHelperFactory,
                   IActionContextAccessor actionContextAccessor)
{

    var urlHelper =
        urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
}

然后根据需要使用它。

答案 1 :(得分:32)

对于 ASP.NET Core 3.x 应用程序,只需将$CredsUserName = 'domain\user' $CredsPassword = 'password' $Domain = "<FQDN of the AD domain>/" $GroupPath = "CN=<UserGroup>...." $UserPath = "CN=<UserDN>...." $Group = [adsi]::new("LDAP://$($Domain)$($GroupPath)",$CredsUserName,$CredsPassword) $Group.member.Add($UserPath) $Group.CommitChanges() LinkGenerator注入到您的控制器或服务中即可。它们应该已经在IHttpContextAccessor中可用。

DI

如果您的应用无法解析using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; namespace Coding-Machine.NET { public class MyService { private readonly IHttpContextAccessor _accessor; private readonly LinkGenerator _generator; public MyService(IHttpContextAccessor accessor, LinkGenerator generator) { _accessor = accessor; _generator = generator; } private string GenerateConfirmEmailLink() { var callbackLink = _generator.GetUriByPage(_accessor.HttpContext, page: "/Account/ConfirmEmail", handler: null, values: new {area = "Identity", userId = 123, code = "ASDF1234"}); return callbackLink; } } } ,只需将其添加到IHttpContextAccessor

DI

答案 2 :(得分:14)

Net Core 2.0

service.AddMvc()

之后添加此内容
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(factory =>
{
    var actionContext = factory.GetService<IActionContextAccessor>()
                                   .ActionContext;
    return new UrlHelper(actionContext);
});

答案 3 :(得分:3)

ASP.NET Core 2.0

安装

PM> Install-Package AspNetCore.IServiceCollection.AddIUrlHelper

使用

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

免责声明:此套餐的作者

答案 4 :(得分:2)

对于ASP.Net Core 2.0 ,您不得插入IUrlHelper。可作为控制器的属性使用。 ControllerBase.Url是IUrlHelper实例。

答案 5 :(得分:1)

对于.Net Core 2.0

services.AddMvc();

services.AddScoped<IUrlHelper>(x =>
{
   var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
   var factory = x.GetRequiredService<IUrlHelperFactory>();
   return factory.GetUrlHelper(actionContext);
});