Search code examples
asp.net-mvcurl-routingroutesmaproute

How can i catch parameter on maproute?


How can i retrieve certain a section on routemap pattern.For instance i have a routemap pattern on my config file as routes.MapRoute("", "Post/{slug}", new { controller = "Post", action = "Index" }) and i want to catch slug parameter inside global.asax.I tried as followed but it returns null.

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"]);
    }
}

Solution

  • You can try this:

    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"]);
         }
    }