在ASP.NET Core中注入IUrlHelper

编程入门 行业动态 更新时间:2024-10-18 14:18:08
本文介绍了在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.

推荐答案

对于 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); }

然后根据需要使用它.

更多推荐

在ASP.NET Core中注入IUrlHelper

本文发布于:2023-11-14 04:19:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   ASP   IUrlHelper   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!