与ASP.NET 5中的RoutedData.GetRequiredString等效
我有几种HtmlHelper扩展方法,用于创建导航栏按钮——一种用于上下文相关的帮助链接。在扩展方法中,我需要知道当前控制器的名称和操作,例如:与ASP.NET 5中的RoutedData.GetRequiredString等效,asp.net,asp.net-mvc-routing,asp.net-core,Asp.net,Asp.net Mvc Routing,Asp.net Core,我有几种HtmlHelper扩展方法,用于创建导航栏按钮——一种用于上下文相关的帮助链接。在扩展方法中,我需要知道当前控制器的名称和操作,例如: var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action"); var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller"); 由于Ro
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
由于RoutedData上不再有GetRequiredString()方法,我可以在ASP.NET 5中使用什么来获取此信息?您可以自己创建扩展
namespace Microsoft.AspNet.Mvc
{
public static class HelperExtensions
{
public static string GetRequiredString(this RouteData routeData, string keyName)
{
object value;
if(!routeData.Values.TryGetValue(keyName, out value))
{
throw new InvalidOperationException($"Could not find key with name '{keyName}'");
}
return value?.ToString();
}
}
}
工作得很好。谢谢顺便说一句,如果其他人也在做同样的事情,您可能还想知道用什么来代替
UrlHelper.GetContentUrl()
。这就是我正在使用的-似乎可以作为IUrlHelper使用var urlHelper=htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelper));var contentUrl=urlHelper.Content(url)代码>