我怎样才能在maproute上捕获参数?

时间:2014-05-21 07:39:34

标签: asp.net-mvc url-routing routes maproute

如何在路由映射模式上检索某个部分。例如我在我的配置文件上有一个路由映射模式为routes.MapRoute("", "Post/{slug}", new { controller = "Post", action = "Index" }),我想在global.asax中捕获slug参数。我尝试如下,但它返回空。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var context = base.Context;
    if (context != null)
    {
        Response.Write(context.Request.RequestContext.RouteData.Values["slug"]);
    }
}

2 个答案:

答案 0 :(得分:0)

我认为当触发BeginRequest事件时,RouteData尚未解析。您可以改用EndRequest。

protected void Application_EndRequest(object sender, EventArgs e)
{
    var context = base.Context;
    if (context != null)
    {
        Response.Write(context.Request.RequestContext.RouteData.Values["slug"]);
    }
}

为了确保使用正确的路线并且实际提供了slug参数,我建议Route debugger

答案 1 :(得分:0)

你可以试试这个:

protected void Application_BeginRequest(object sender, EventArgs e)
{
     var httpContext = ((MvcApplication)sender).Context;
     var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

     if (currentRouteData.Values["slug"] != null)
     {
         Response.Write(currentRouteData.Values["slug"]);
     }
}