1

我想做类似的事情:

对于控制器所在的类别CategoryController

www.mysite.com/some-category
www.mysite.com/some-category/sub-category
www.mysite.com/some-category/sub-category/another //This could go on ..

问题是:www.mysite.com/some-product需要指向一个ProductController. 通常这会映射到同一个控制器。

那么,如何拦截路由,以便检查参数是类别还是产品并相应地进行路由。

我试图避免有类似的东西,www.mysite.com/category/some-category或者www.mysite.com/product/some-product我觉得它会在 SEO 方面表现更好。当我可以拦截路由时,我将根据一些规则转发到一个产品/类别,这些规则会查看每个等的 slug。

4

1 回答 1

2

您可以编写自定义路由来实现此目的:

public class CategoriesRoute: Route
{
    public CategoriesRoute()
        : base("{*categories}", new MvcRouteHandler())
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }

        string categories = rd.Values["categories"] as string;
        if (string.IsNullOrEmpty(categories) || !categories.StartsWith("some-", StringComparison.InvariantCultureIgnoreCase))
        {
            // The url doesn't start with some- as per our requirement =>
            // we have no match for this route
            return null;
        }

        string[] parts = categories.Split('/');

        // for each of the parts go hit your categoryService to determine whether
        // this is a category slug or something else and return accordingly
       if (!AreValidCategories(parts)) 
       {
           // The AreValidCategories custom method indicated that the route contained
           // some parts which are not categories => we have no match for this route
           return null;
       }

        // At this stage we know that all the parts of the url are valid categories =>
        // we have a match for this route and we can pass the categories to the action
        rd.Values["controller"] = "Category";
        rd.Values["action"] = "Index";
        rd.Values["categories"] = parts;

        return rd;
    }
}

这将像这样注册:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add("CategoriesRoute", new CategoriesRoute());

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

然后你可以有相应的控制器:

public class CategoryController: Controller
{
    public ActionResult Index(string[] categories)
    {
        ... The categories action argument will contain a list of the provided categories
            in the url
    }
}
于 2014-10-26T12:40:14.500 回答