How to convert query string parameters to route in asp.net mvc 4

妖精的绣舞 提交于 2019-12-04 17:36:25

You have to declare custom routes before the default routes. Otherwise it will be mapping to {controller}/{action}/{id}.


Global.asax typically looks like this:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

If you created an Area named Blogs, there is a corresponding BlogsAreaRegistration.cs file that looks like this:

public class BlogsAreaRegistration : AreaRegistration 
{
    public override string AreaName 
    {
        get 
        {
            return "Blogs";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context) 
    {
        context.MapRoute(
            "Admin_default",
            "Blogs/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

Hyphens are sometimes treated like forward slashes in routes. When you are using the route blogs/students/john-doe, my guess is that it is matching the Area pattern above using blogs/students/john/doe, which would result in a 404. Add your custom route to the BlogsAreaRegistration.cs file above the default routes.

Try adding the parameter to the route:

routes.MapRoute(
    name: "StudentBlogs",
    url: "blogs/student/{name}",
    defaults: new { controller = "Student", action="Index", name = UrlParameter.Optional}
);

Try adding a constraint for the name parameter:

routes.MapRoute(
    name: "StudentBlogs",
    url: "blogs/student/{name}",
    defaults: new { controller = "Student", action="Index" },
    constraints: new { name = @"[a-zA-Z-]+" }
);

Dashes are a bit weird in MVC at times.. because they are used to resolve underscores. I will remove this answer if this doesn't work (although.. it should).

This has the added benefit of failing to match the route if a URL such as /blogs/student/12387 is used.

EDIT:

If you have controllers with the same name.. you need to include namespaces in both of your routes in each area. It doesn't matter where the controllers are.. even if in separate areas.

Try adding the appropriate namespace to each of the routes that deal with the Student controller. Somewhat like this:

routes.MapRoute(
    name: "StudentBlogs",
    url: "blogs/student/{name}",
    defaults: new { controller = "Student", action="Index" },
    namespaces: new string[] { "Website.Areas.Blogs.Controllers" }
);

..and perhaps Website.Areas.Admin.Controllers for the one in the admin area.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!