当前位置: 首页 > 编程语言 > C#

在ASP.NETCore中注入IUrlHelper分享

时间:2023-04-10 10:56:24 C#

在ASP.NETCore中注入IUrlHelperRC1中,IUrlHelper可以在服务中注入services.AddMvc(),在启动类中使用services.AddMvc())这个没有在RC2中工作时间更长。有谁知道如何在RC2中执行此操作,因为新的UrlHelper需要一个ActionContext对象。不确定如何将它从控制器中取出。此问题存在于ASP.NETCoreRC2的github存储库中。不要注入IUrlHelper,而是使用IUrlHelperFactory。听起来您需要注入IActionContextAccessor,因为Controller不再具有公共属性ActionContext。注册一个依赖:services.AddSingleton();然后依赖它:publicSomeService(IUrlHelperFactoryurlHelperFactory,IActionContextAccessoractionContextAccessor){varurlHelper=urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);然后根据需要使用它。对于NetCore2.0,在service.AddMvc()services.AddSingleton();之后添加这个services.AddScoped(factory=>{varactionContext=factory.GetService().ActionContext;returnnewUrlHelper(actionContext);});ASP.NETCore2.0安装PM>Install-PackageAspNetCore.IServiceCollection.AddIUrlHelper使用publicvoidConfigureServices(IServiceCollectionservices){...services.AddUrlHelper();...}免责声明:本包作者是针对.NetCore2.0以上版本的C#学习教程:将IUrlHelper分享的所有内容注入到ASP.NETcore中。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——services.AddMvc();services.AddScoped(x=>{varactionContext=x.GetRequiredService().ActionContext;varfactory=x.GetRequiredService();returnfactory.GetUrlHelper(actionContext);});本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: