MVC4 Can';找不到合适的路线
本文关键字:找不到 Can MVC4 | 更新日期: 2023-09-27 18:20:54
我需要将以下URL路由到控制器:
- /伦敦航班
- /圣彼得堡航班
在Global.asax中定义正确的URL映射字符串是什么?
我试过:
- "{countrycode}/{keyword}-{destination}"->适用于1但不适用于2
- "{countrycode}/{keyword}-{*destination}"->异常
我希望有人能帮助我。
/de/flight-st-petersburg
由于已知错误而无法工作。您有两个选项:
- 用斜线分隔关键字和目的地:
{countrycode}/{keyword}/{destination}
- 使用模型活页夹,如下所示:
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) {
}
路由部分用斜线分隔,因此我认为您需要使用
{countrycode}/{keyword}/{*destination}