【问题标题】:Asp.Net Custom Routing and custom routing and add category before controllerAsp.Net 自定义路由和自定义路由并在控制器之前添加类别
【发布时间】:2011-10-10 13:36:30
【问题描述】:

我刚刚学习 MVC,想为我的网站添加一些自定义路由。

我的网站分为多个品牌,因此在访问网站的其他部分之前,用户将选择一个品牌。我不想将所选品牌存储在某处或将其作为参数传递,而是希望将其作为 URL 的一部分,以便例如访问 NewsControllers 索引操作而不是 "mysite.com/news"喜欢使用“mysite.com/brand/news/”

我真的很想添加一条路线,说明如果 URL 有品牌,则正常转到控制器/动作并通过品牌...这可能吗?

谢谢

C

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-routing


    【解决方案1】:

    是的,这是可能的。首先,您必须创建一个RouteConstraint 以确保选择了一个品牌。如果尚未选择品牌,则此路线应该失败,并且应该遵循重定向到品牌选择器的操作路线。 RouteConstraint 应该如下所示:

    using System; 
    using System.Web;  
    using System.Web.Routing;  
    namespace Examples.Extensions 
    { 
        public class MustBeBrand : IRouteConstraint 
        { 
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
            { 
                // return true if this is a valid brand
                var _db = new BrandDbContext();
                return _db.Brands.FirstOrDefault(x => x.BrandName.ToLowerInvariant() == 
                    values[parameterName].ToString().ToLowerInvariant()) != null; 
            } 
        } 
    } 
    

    然后,如下定义您的路线(假设您的品牌选择器是主页):

    routes.MapRoute( 
        "BrandRoute",
        "{controller}/{brand}/{action}/{id}",
        new { controller = "News", action = "Index", id = UrlParameter.Optional }, 
        new { brand = new MustBeBrand() }
    ); 
    
    routes.MapRoute( 
        "Default",
        "",
        new { controller = "Selector", action = "Index" }
    ); 
    
    routes.MapRoute( 
        "NotBrandRoute",
        "{*ignoreThis}",
        new { controller = "Selector", action = "Redirect" }
    ); 
    

    那么,在你的SelectorController

    public ActionResult Redirect()
    {
        return RedirectToAction("Index");
    }
    
    public ActionResult Index()
    {
        // brand selector action
    }
    

    如果您的主页不是品牌选择器,或者网站上有其他非品牌内容,则此路由不正确。您将需要 BrandRoute 和 Default 之间的其他路由,这些路由与您的其他内容相匹配。

    【讨论】:

    • 非常感谢辅导员本,让我走上了正轨!!
    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 2015-10-12
    • 2013-09-30
    • 2018-09-14
    相关资源
    最近更新 更多