How do I define a catch-all route for an ASP.NET MVC site?

巧了我就是萌 提交于 2019-12-10 12:50:00

问题


I have a news site with articles tagged in categories.

My Controller is called "Category" and this URL:

http://mysite.com/Category/Sport

passes Sport to action Index in controller Category.

I want to allow the following URLs:

http://mysite.com/Sport/Hockey
http://mysite.com/Sport/Football
http://mysite.com/Science/Evolution

Which passes all category information to action Index in controller Category.

How do I create a catch-all route that handles all these and shuttles them to category?


回答1:


There's a pretty good response to my question along these lines here.




回答2:


You can do it like this:

routes.MapRoute("Default", "{category}/{subcategory}",
    new { controller = "CategoryController", action = "Display", id = "" }
);

and then in your controller:

public class CategoryController : Controller
{
    public ActionResult Display(string category, string subcategory)
    {
        // do something here.
    }
}

Do not that any the route above will be used for ALL routes (you can't have a About page etc unless you specify explicit routes before the above one).

You could however include a custom constraint to limit the route to only existing categories. Something like:

public class OnlyExistingCategoriesConstraint : IRouteConstraint
{
    public bool Match
        (
            HttpContextBase httpContext,
            Route route,
            string parameterName,
            RouteValueDictionary values,
            RouteDirection routeDirection
        )
    {
        var category = route.DataTokens["category"];
        //TODO: Look it up in your database etc


        // fake that the category exists
        return true;
    }
}

Which you use in your route like this:

routes.MapRoute("Default", 
    "{category}/{subcategory}",
    new { controller = "CategoryController", action = "Display", id = "" },
    new { categoryExists = new OnlyExistingCategoriesConstraint() }
);

In that way it won't interfere with your other defined routes.



来源:https://stackoverflow.com/questions/218845/how-do-i-define-a-catch-all-route-for-an-asp-net-mvc-site

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