开发者

Asp.Net Custom Routing and custom routing and add category before controller

开发者 https://www.devze.com 2023-04-12 04:03 出处:网络
I\'m just learning MVC and want to add some custom routing to my site. My site is split into brands so before accessing other parts of the site the user will select a brand.Rather than storing the ch

I'm just learning MVC and want to add some custom routing to my site.

My site is split into brands so before accessing other parts of the site the user will select a brand. Rather than storing the chosen brand somewhere or passing it as a parameter I would like to make it part of the URL so to access the NewsControllers index action for example rather than "mysite.com/news" I wo开发者_运维问答uld like to use "mysite.com/brand/news/".

I just really want to add a route which says if a URL has a brand, go to the controller/action as normal and pass through the brand...is this possible?

Thanks

C


Yes, this is possible. First, you must create a RouteConstraint to insure that a brand has been chosen. If a brand has not been chosen, this route should fail, and a route to an action to redirect to the brand selector should follow. The RouteConstraint should look like this:

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; 
        } 
    } 
} 

Then, define your Routes as follows (assuming that your brand selector is the home page):

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" }
); 

Then, in your SelectorController:

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

public ActionResult Index()
{
    // brand selector action
}

If your home page is not the brand selector, or there is other non-brand content on the site, then this routing is not correct. You will need additional routes between BrandRoute and Default which match routes to your other content.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号