简体   繁体   English

ASP.Net MVC 5获取属性路由值

[英]ASP.Net MVC 5 get attribute routing values

I switch from the old attribute routing library to the bundled asp.net MVC 5 routing. 我从旧的属性路由库切换到捆绑的asp.net MVC 5路由。 But now my lang route value is null in the Application_AcquireRequestState 但是现在我的lang路由值在Application_AcquireRequestStatenull

// rootcontroller.cs       
[HttpGet]
[Route("")]
[Route("{lang}")]
// old attribute routing worked:
// [GET("/{lang}")]
public ActionResult Index(string lang =null)
{
    return View();
}

// global.asax
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    var handler = Context.Handler as MvcHandler;

    if (handler == null)
       return;
    var routeData = handler.RequestContext.RouteData;

    var lang = routeData.Values["lang"];   // null instead for example 'de'
    // ... set current culture
}

Attribute routing in MVC 5 uses a special key named "MS_DirectRouteMatches" which contains a list of RouteData elements. MVC 5中的属性路由使用名为“ MS_DirectRouteMatches”的特殊键,该键包含RouteData元素列表。 I am not sure why they did this as it seems that only one RouteData element is possible. 我不确定他们为什么这样做,因为似乎只有一个RouteData元素是可能的。 So you need to check for this key and use its first value if it exists. 因此,您需要检查此键并使用它的第一个值(如果存在)。

var routeData = handler.RequestContext.RouteData;

if (routeData != null)
{
    if (routeData.Values.ContainsKey("MS_DirectRouteMatches"))
    {
        routeData = ((IEnumerable<RouteData>)routeData.Values["MS_DirectRouteMatches"]).First();
    }
}

var lang = routeData.Values["lang"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM