Can I constrain a route parameter to a certain typ

2019-08-26 16:53发布

问题:

I have the following route:

routes.MapRoute(
    "Search",                                               // Route name
    "Search/{affiliateId}",                                 // URL with parameters
    new { controller = "Syndication", action = "Search" }   // Parameter defaults
);

Is there a way I can ensure "affiliateId" is a valid Guid? I'm using MVCContrib elsewhere in my site and I'm fairly it provides a way to implement this kind of constraint.... I just don't know what it is!

回答1:

You could write regex constraints:

routes.MapRoute(
    "Search",                                               // Route name
    "Search/{affiliateId}",                                 // URL with parameters
    new { controller = "Syndication", action = "Search" },   // Parameter defaults
    new { affiliateId = "SOME REGEX TO TEST GUID FORMAT" } // constraints
);


回答2:

I've never heard of this. I fear it would cause some confusion if you mistakenly used the wrong type for the affiliateId parameter in one of your action methods.