我想通过依赖注入来使用 IUrlHelper,以便能够使用它的功能为不同的休息端点生成 uri。我似乎无法弄清楚如何从头开始创建 UrlHelper,因为它在 MVC 6 中发生了变化,并且 MVC 不会自动在 IoC 控制器中提供该服务。
设置是我的控制器将内部模型接收到 api 模型转换器类并使用 IUrlHelper(全部通过依赖注入)。
如果有更好的替代 IUrlHelper/UrlHelper 我可以用来为我的 WebApi 操作/控制器生成 Uris,我愿意接受建议。
我想通过依赖注入来使用 IUrlHelper,以便能够使用它的功能为不同的休息端点生成 uri。我似乎无法弄清楚如何从头开始创建 UrlHelper,因为它在 MVC 6 中发生了变化,并且 MVC 不会自动在 IoC 控制器中提供该服务。
设置是我的控制器将内部模型接收到 api 模型转换器类并使用 IUrlHelper(全部通过依赖注入)。
如果有更好的替代 IUrlHelper/UrlHelper 我可以用来为我的 WebApi 操作/控制器生成 Uris,我愿意接受建议。
UrlHelper 需要当前的操作上下文,我们可以从 ActionContextAccessor 获取它。我正在使用这个:
services.AddScoped<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x =>
{
var actionContext = x.GetService<IActionContextAccessor>().ActionContext;
return new UrlHelper(actionContext);
});
现在,您可以将 IUrlHelper 直接注入到任何需要它的东西中,而无需跳过 IHttpContextAccessor 。
这种方法现在已经过时了。看看下面的更新。
代替services.AddTransient<IUrlHelper, UrlHelper>()
或尝试直接注入 IUrlHelper 您可以注入 IHttpContextAccessor 并从那里获取服务。
public ClassConstructor(IHttpContextAccessor contextAccessor)
{
this.urlHelper = contextAccessor.HttpContext.RequestServices.GetRequiredService<IUrlHelper>();
}
除非只是一个 bug,否则用 UrlHelper 添加 IUrlHelper 服务是行不通的。
更新 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();
}
}
ASP.NET 核心 2.0
安装
PM> Install-Package AspNetCore.IServiceCollection.AddIUrlHelper
利用
public void ConfigureServices(IServiceCollection services)
{
...
services.AddUrlHelper();
...
}
免责声明:此软件包的作者
对于 .NET 核心 3.1
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>()
.AddScoped(x =>
x.GetRequiredService<IUrlHelperFactory>()
.GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext)); //Inject UrlHelp for