ASP .Net MVC路由:仅使用字符串ID的URL

dri*_*weg 10 asp.net-mvc url-routing

很简单的问题,但我找不到答案:

我{controller}/{action}/{id}在global.asax中有默认模式.

当微软和苹果存储在数据库中时,我还需要一些东西,比如www.example.com/microsoft或www.example.com/appleid.使用默认模式为:www.example.com/brands/detail/microsoft

任何想法模式应该如何?我尝试过:{id}并设置控制器和操作brands,detail它可以满足我的需求,但会破坏所有其他模式.

谢谢

tva*_*son 6

我会建议一个单独的路由,其约束条件是id无法与您的某个控制器匹配,或者必须与数据库中的某个ID匹配.如果符合条件,则在默认路由之前列出它以使其首先匹配.

使用简单正则表达式获得固定约束的示例,尽管您可能希望创建一个源自IRouteConstraint的自定义约束,该约束动态地限制值.

routes.MapRoute(
  "Brands",
  "{id}",
  new { controller = "brand", action = "detail" },
  new { id = "^(Microsoft)|(Apple)$" }
);
Run Code Online (Sandbox Code Playgroud)

您可以查看http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx以获取更多想法.


Shy*_*yju 5

您的路线顺序很重要.因此,创建一个处理所有可用控制器的第一个路由定义,然后提及一个将处理其余请求的控制器.你会处理www.yousite.com/apple那种请求

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 = "" });
Run Code Online (Sandbox Code Playgroud)

现在创建一个名为FromValuesListContraintIRouteConstraint 的新类

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

让您Profile在Home中的操作方法读取参数值并从数据库中获取数据.

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

因此,每当一个请求到来时,它将检查它是否是一个可用的控制器(你在第一个路由定义中传递给FromValuesListContraint类构造函数),如果可用,那么它将用于该路由,否则,它将用于一般(默认)路由被提到作为第二条路线.

在此示例中,Home,Account和OtherOnes是我可用的控制器.无论何时向项目添加新控制器,都要将其添加到FromValuesListConstraint类构造函数的构造函数中.

简单地说它就像捕获一些特定的异常一样,如果没有捕获它们就会转到一般异常!:)(只是一个例子来理解)