Asp.Net自定义路由和自定义路由并在控制器之前添加类别

car*_*rok 1 asp.net-mvc asp.net-mvc-routing

我只是在学习MVC,并想在我的网站上添加一些自定义路由.

我的网站被拆分为品牌,因此在访问网站的其他部分之前,用户将选择一个品牌.我没有将所选品牌存储在某个地方或将其作为参数传递,而是希望将其作为URL的一部分,以便访问NewsControllers索引操作,而不是"mysite.com/news"我想使用"mysite.com" /品牌/新闻/".

我真的想添加一条路线,说明如果一个URL有品牌,就像正常一样去控制器/行动并通过品牌......这可能吗?

谢谢

C

cou*_*ben 8

是的,这是可能的.首先,您必须创建一个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; 
        } 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

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

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" }
); 
Run Code Online (Sandbox Code Playgroud)

然后,在你的SelectorController:

public ActionResult Redirect()
{
    return RedirectToAction("Index");
}

public ActionResult Index()
{
    // brand selector action
}
Run Code Online (Sandbox Code Playgroud)

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