我只是学习MVC,并希望添加一些自定义路由到我的网站。
我的网站是分为品牌,所以在访问网站的其他部分之前,用户将选择一个品牌。与其将所选品牌存储在某个地方或将其作为参数传递,我希望将其作为URL的一部分,例如,为了访问NewsControllers索引操作,而不是使用"mysite.com/news“,而是使用"mysite.com/ brand /news/”。
我只想添加一条路线,上面写着如果一个URL有一个品牌,就像往常一样去控制器/动作,并通过brand...is --这是可能的吗?
谢谢
C
发布于 2011-10-10 15:37:30
是的,这是可能的。首先,您必须创建一个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和默认,这是匹配路由到您的其他内容。
https://stackoverflow.com/questions/7713590
复制相似问题