Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
与ASP.NET 5中的RoutedData.GetRequiredString等效_Asp.net_Asp.net Mvc Routing_Asp.net Core - Fatal编程技术网

与ASP.NET 5中的RoutedData.GetRequiredString等效

与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

我有几种HtmlHelper扩展方法,用于创建导航栏按钮——一种用于上下文相关的帮助链接。在扩展方法中,我需要知道当前控制器的名称和操作,例如:

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)