我只是在学习MVC,并想在我的网站上添加一些自定义路由.
我的网站被拆分为品牌,因此在访问网站的其他部分之前,用户将选择一个品牌.我没有将所选品牌存储在某个地方或将其作为参数传递,而是希望将其作为URL的一部分,以便例如访问NewsControllers索引操作而不是“mysite.com/news”我想使用“mysite.com” /品牌/新闻/”.
我真的想添加一条路线,上面写着一个URL是否有品牌,正常进入控制器/动作并通过品牌……这可能吗?
谢谢
C
解决方法
是的,这是可能的.首先,您必须创建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}",action = "Redirect" } );
然后,在你的SelectorController中:
public ActionResult Redirect() { return RedirectToAction("Index"); } public ActionResult Index() { // brand selector action }
如果您的主页不是品牌选择器,或者网站上有其他非品牌内容,则此路由不正确.您将需要BrandRoute和Default之间的其他路线,这些路线与您的其他内容的路线相匹配.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。