简体   繁体   中英

ASP.Net MVC 5 get attribute routing values

I switch from the old attribute routing library to the bundled asp.net MVC 5 routing. But now my lang route value is null in the Application_AcquireRequestState

// 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. I am not sure why they did this as it seems that only one RouteData element is possible. 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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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