ASP .Net MVC Routing: Url only with string ID

后端 未结 2 1869
陌清茗
陌清茗 2021-02-08 10:46

very simple question but I couldn\'t find an answer for this:

I have the default {controller}/{action}/{id} pattern in my global.asax.

I ne

2条回答
  •  情深已故
    2021-02-08 11:05

    Your route order matters. So create a first route definition which handles all available controllers and then mention one which will handle the rest of the requests. There you will handle the www.yousite.com/apple kind of request

    routes.MapRoute("Default",  // Route name
                      "{controller}/{action}/{id}", // URL with parameters
                        new { controller = "Home", action = "Index", id = "" },
                        new { controller = new FromValuesListConstraint("Home", "Account","OtherOne") }
                    );
    
     // to handle personalize user url
    routes.MapRoute("user","{url}", new {controller="Home",action="Profile",url = "" });
    

    Now create a new class called FromValuesListContraint which inherit from IRouteConstraint

    public class FromValuesListConstraint : IRouteConstraint
    {
        private string[] _values;
    
        public FromValuesListConstraint(params string[] values)
        {
            this._values = values; 
        }
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName,
        RouteValueDictionary values, RouteDirection routeDirection)
        {
            // Get the value called "parameterName" from the
            // RouteValueDictionary called "value"
    
            string value = values[parameterName].ToString();
    
            // Return true is the list of allowed values contains
            // this value.
    
            for (int i = 0; i < _values.Length; i++)
                if (SContains(_values[i], value, StringComparison.OrdinalIgnoreCase ))
                    return true;
    
            return false;
        }    
    
        public bool SContains(string source, string toCheck, StringComparison comp)
        {
            return source.IndexOf(toCheck, comp) >= 0;
        }
    }
    

    Have your Profile action method in Home read the parameter value and get data from your database.

     public ActionResult Profile(string url)
     {
        //url variable will have apple or microsoft . You may get data from db and return a view now.
     }
    

    So whenever a request comes, It will check whether it is a controller available ( which you passed into the FromValuesListContraint class constructor in your first route definition), if available then it will go for that routing, else, it will go for the general (default) route mentioned as the second route.

    In this example, Home, Account and OtherOnes are my available controllers. whenever you add a new controller to your project, you want to add that to the constrctor of FromValuesListConstraint class constructor.

    Simply saying it works like Catching some specific exception and going to the general exception if none of them are caught! :) (just an example to understand)

提交回复
热议问题