I have a controller that contains two different Get methods. One takes an int value and the other takes a String value, as shown below:
public class AccountController : ApiController { public String GetInfoByString(String sUserInput) { return "GetInfoByString received: " + sUserInput; } public String GetInfoByInt(int iUserInput) { return "GetInfoByInt received: " + iUserInput; } }
My RouteConfig.cs is intact and looks like this:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
My WebApiConfig.cs is also untouched and looks like this:
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
I would like to get into the web interface using one link:
// Hit GetInfoByInt http://localhost:XXXX/api/account/1 // Hit GetInfoByString http://localhost:XXXX/api/account/abc
I can hit the first case just fine, but whenever I try to get into the second case, I get the following error:
<Error> <Message>The request is invalid.</Message> <MessageDetail> The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'TestProject.String GetInfoByInt(Int64)' in 'TestProject.Controllers.AccountController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. </MessageDetail> </Error>
Is it possible to use the Get method depending on whether the user provided String or int ? I assume that changes should be made to RouteConfig or WebApiConfig, but I'm not too sure how to approach this. Maybe this is just an easy solution?
Also, if that matters, I would like to be able to use GetInfoByString with a String that contains both letters and numbers, such as 'ABC123' or '123ABC' . GetInfoByInt may be something like '123'
I would really like to stick to one controller, and not split it into multiple controllers, if possible.
Thanks in advance for your help.