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

问题描述

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

In RC1, IUrlHelper could be injected in services (with services.AddMvc() in startup class)

这在 RC2 中不再起作用.有没有人知道如何在 RC2 中做到这一点,因为刚刚新建一个 UrlHelper 需要一个 ActionContext 对象.不知道如何在控制器之外获得它.

This doesn't work anymore in RC2. Does anybody know how to do it in RC2 as just newing up a UrlHelper requires an ActionContext object. Don't know how to get that outside a controller.

推荐答案

.NET Core 3+ 和 .NET 5 更新(2020 及更高版本)

使用 LinkGenerator,如@Dmitry Pavlov 的对此线程的回答中所述.它可以作为 Web 框架的一部分进行注入,并与控制器中已有的 HttpContext 一起使用,或者通过注入 IHttpContextAccessor 可在其他服务中访问.

Use LinkGenerator as detailed in @Dmitry Pavlov's answer on this thread. It's injectable as part of the web framework, and works with the HttpContext already available in controllers, or accessible in other services by injecting the IHttpContextAccessor.

对于 ASP.NET Core RC2 有一个 问题github 存储库.不要注入 IUrlHelper,而是使用 IUrlHelperFactory.听起来您还需要将 IActionContextAccessor 作为 Controller 注入,不再具有公共属性 ActionContext.

For ASP.NET Core RC2 there is an issue for this on the github repo. Instead of injecting the IUrlHelper, take an IUrlHelperFactory. It also sounds like you'd need the IActionContextAccessor injected as a Controller no longer has a public property ActionContext.

注册依赖:

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

那就靠它吧:

public SomeService(IUrlHelperFactory urlHelperFactory,
                   IActionContextAccessor actionContextAccessor)
{

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

然后按照您认为合适的方式使用它.

Then use it as you see fit.

这篇关于在 ASP.NET Core 中注入 IUrlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:22