问题描述
我目前正在尝试做一些在 ASP.NET 4 中非常简单直接的事情,但现在在 ASP.NET 5 中并非如此.
I'm currently trying to do something that was dead simple and straight forward in ASP.NET 4 however this ins't the case now in ASP.NET 5.
以前使用 UrlHelper 非常简单:
Previously to use the UrlHelper it was dead simple:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
但是,我无法终生思考如何使用新的 UrlHelper.我正在查看测试用例,要么我完全愚蠢,要么我遗漏了一些东西,我似乎无法弄清楚.任何帮助解决这个问题都会很棒.
However I can't for the life of me wrap my head around how to use the new UrlHelper. I'm looking at the test cases and either I'm completely daft or I'm missing something and I can't seem to figure it out. Any help here in clearing up this would be great.
推荐答案
更新 - 发布 RC2
正如@deebo 提到的,您不再可以直接从 DI 获得 IUrlHelper
.相反,您需要将 IUrlHelperFactory
和 IActionContextAccessor
注入到您的类中,并使用它们来获取 IUrlHelper
实例,如下所示:
As @deebo mentioned, you no longer can get an IUrlHelper
directly from DI. Instead you need to inject an IUrlHelperFactory
and an IActionContextAccessor
into your class and use them to get the IUrlHelper
instance as in:
public MyClass(IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionAccessor)
{
this.urlHelperFactory = urlHelperFactory;
this.actionAccessor = actionAccessor;
}
public void SomeMethod()
{
var urlHelper = this.urlHelperFactory.GetUrlHelper(this.actionAccessor.ActionContext);
}
你还需要在你的启动类中注册(IUrlHelperFactory
已经默认注册了):
You need to also register the in your startup class (IUrlHelperFactory
is already registered by default):
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
请记住,这只有在获得 actionContext 的代码在 MVC/路由中间件之后运行时才有效!(否则 actionAccessor.ActionContext
将为空)
Bear in mind this will only work as long as the code where you get the actionContext is running after the MVC/routing middleware! (Otherwise actionAccessor.ActionContext
would be null)
我已使用 HttpContext.RequestServices
中的 IServiceProvider
检索到 IUrlHelper
.
I have retrieved the IUrlHelper
using the IServiceProvider
in HttpContext.RequestServices
.
通常你手头会有一个 HttpContext
属性:
Usually you will have an HttpContext
property at hand:
在控制器动作方法中你可以这样做:
In a controller action method you can do:
var urlHelper = this.Context.RequestServices.GetRequiredService<IUrlHelper>();
ViewBag.Url = urlHelper.Action("Contact", "Home", new { foo = 1 });
在过滤器中你可以这样做:
In a filter you can do:
public void OnActionExecuted(ActionExecutedContext context)
{
var urlHelper = context.HttpContext.RequestServices.GetRequiredService<IUrlHelper>();
var actionUrl = urlHelper.Action("Contact", "Home", new { foo = 1 });
//use actionUrl ...
}
另一种选择是利用内置的依赖注入,例如,您的控制器可以具有如下构造函数,并且在运行时将提供 IUrlHelper
实例:
Another option would be taking advantage of the built-in dependency injection, for example your controller could have a constructor like the following one and at runtime an IUrlHelper
instance will be provided:
private IUrlHelper _urlHelper;
public HomeController(IUrlHelper urlHelper)
{
_urlHelper = urlHelper;
}
这篇关于无法使用 UrlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!