开发者

How to make multiple routing on same controller

开发者 https://www.devze.com 2023-03-27 16:49 出处:网络
What I want to do is like Facebook profile page which is (facebook.com/username) , I\'d like to do the same thing ww开发者_如何学JAVAw.myapplication/username , is there any routing method ??To route t

What I want to do is like Facebook profile page which is (facebook.com/username) , I'd like to do the same thing ww开发者_如何学JAVAw.myapplication/username , is there any routing method ??


To route to a profile page, you need a route with a RouteConstraint to check the validity of the username. Your route must be the first route, and RegisterRoutes in Global.asax.cs should look like this:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Profiles", // Route name
        "{username}", // URL
        new { controller = "Profile", action = "Index" }, // Parameters
        new { username = new MustBeUsername() }

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

}

Then, you must create a RouteConstraint class which will check you database to confirm that the username submitted is valid:

using System; 
using System.Web; 
using System.Web.Routing;  

namespace ExampleApp.Extensions 
{ 
    public class MustBeUsername : IRouteConstraint  
    { 
        public MustBeUsername() { }

        private DbContext _db = new DbContext();

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)    
        {      
            return (_db.Users.Where(u => u.Username == values[parameterName].ToString()).Count() > 0);
        }  
    } 
}

counsellorben

0

精彩评论

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

关注公众号