Reputation: 1177
I'm working on some Web Api methods and ran into a scenario where we are passing in three different type of parameters: Numbers, Strings, and Alphanumeric values.
Here is my routing information:
string alphanumeric = @"^[a-zA-Z]+[a-zA-Z0-9,_ -]*$";
string numeric = @"^\d+$";
config.Routes.MapHttpRoute(
name: "DefaultApiControllerActionName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { action = alphanumeric }
);
config.Routes.MapHttpRoute(
name: "DefaultApiControllerActionId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null,
constraints: new { action = alphanumeric, id = numeric }
);
With this route info I can get either strings and alphanumeric values but not numbers (through the same method). Here is my code:
public IEnumerable<Deliveries> GetByAdvanced(string name)
{
var deliveries = ...
return deliveries;
}
e.g. Example Web API Urls
Now if I add another method just to handle the int value it works perfectly fine. e.g. the code below
public IEnumerable<Deliveries> GetByAdvanced(int id)
{
var deliveries = ...
return deliveries;
}
Is this the correct way accept these values?
Upvotes: 4
Views: 6801
Reputation: 2078
Looking at your example Web API urls they all should work.
I created two simple new web projects using the following configurations:
1) MVC4, Web Api and .NET 4
2) MVC 5, Web Api 2.2 and .NET 4.5.1
I used the the same routing as you presented and the same action method in the controller and all example execution works correctly. How looks your entire web api config file? Have you defined some additional routing on action methods or controller and you didn't show us?
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); string alphanumeric = @"^[a-zA-Z]+[a-zA-Z0-9,_ -]*$"; string numeric = @"^\d+$"; config.Routes.MapHttpRoute( name: "DefaultApiControllerActionName", routeTemplate: "api/{controller}/{action}/{name}", defaults: null, constraints: new { action = alphanumeric } ); config.Routes.MapHttpRoute( name: "DefaultApiControllerActionId", routeTemplate: "api/{controller}/{action}/{id}", defaults: null, constraints: new { action = alphanumeric, id = numeric } ); } }
Controller:
public class DeliveryController : ApiController { public string GetByAdvanced(string name) { return name; } }
BTW. why do you specify constraint for action name?
Upvotes: 0
Reputation: 3237
If it's just going to affect only one method then you may try Attribute Routing in the controller rather than modifying the route config.
Try something like the below
[Route("Api/Deliveries/{id}/{StringVal}/{AlphaVal}")]
public IEnumerable<Deliveries> GetByAdvanced(int id, string StringVal, string AlphaVal)
{
var deliveries = ...
return deliveries;
}
Upvotes: 4