MVC4无法找到正确的路由

时间:2013-07-02 15:48:58

标签: c# .net asp.net-mvc

我需要将以下网址路由到控制器:

  1. /解/飞行伦敦
  2. /解/飞行圣彼得堡
  3. 在Global.asax中定义的URL-Mapping-String是什么?

    我试过了:

    1. “{countrycode} / {keyword} - {destination}” - >适合1但不适合2
    2. “{countrycode} / {keyword} - {* destination}” - >例外!
    3. 我希望有人可以帮助我。

2 个答案:

答案 0 :(得分:1)

由于known bug

/de/flight-st-petersburg无效。您有两个选择:

  1. 使用斜杠分隔关键字和目标:{countrycode}/{keyword}/{destination}
  2. 使用模型绑定器,如下所示:
  3. class CustomIdentifier {
    
       public const string Pattern = @"(.+?)-(.+)";
       static readonly Regex Regex = new Regex(Pattern);
    
       public string Keyword { get; private set; }
       public string Value { get; private set; }
    
       public static CustomIdentifier Parse(string identifier) {
    
          if (identifier == null) throw new ArgumentNullException("identifier");
    
          Match match = Regex.Match(identifier);
    
          if (!match.Success)
             throw new ArgumentException("identifier is invalid.", "identifier");
    
          return new CustomIdentifier {
             Keyword = match.Groups[1].Value,
             Value = match.Groups[2].Value
          };
       }
    }
    
    class CustomIdentifierModelBinder : IModelBinder {
    
       public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
          return CustomIdentifier.Parse(
             (string)bindingContext.ValueProvider.GetValue(bindingContext.ModelName).RawValue
          );
       }
    }
    

    然后在Application_Start上注册:

    void RegisterModelBinders(ModelBinderDictionary binders) {
       binders.Add(typeof(CustomIdentifier), new CustomIdentifierModelBinder());
    }
    

    使用以下路线:

    routes.MapRoute(null, "{countryCode}/{id}",
       new { },
       new { id = CustomIdentifier.Pattern });
    

    你的行动:

    public ActionResult Flight(CustomIdentifier id) {
    
    }
    

答案 1 :(得分:0)

路线部分用斜线分隔,因此您需要使用我认为:

{countrycode}/{keyword}/{*destination}