MVC4 Web API with multiple parameters

I have a controller named LoginController with a Get method with a signature:

public string Get(string Key, string Code, string UserID, string Password) 

I want to be able to call it with a call like:

 http://localhost:1234/api/Login/KeyValue/CodeValue/UserValue/PasswordValue 

I can't get this to work. If I make a call with:

 http://localhost:1234/api/Login?Key=KeyValue&Code=CodeValueUserID=UserValue&Password=PasswordValue 

Call completed successfully.

I tried adding routes like below to Global.asax

  routes.MapHttpRoute(name: "Login", routeTemplate: "api/{controller}/{action}/{Key}/{Code}/{UserID}/{Password}", defaults: new { Key = UrlParameter.Optional, Code = UrlParameter.Optional, UserID = UrlParameter.Optional, Password = UrlParameter.Optional }); 

or

  routes.MapHttpRoute(name: "Login", routeTemplate: "api/{controller}/{Key}/{Code}/{UserID}/{Password}", defaults: new { Key = UrlParameter.Optional, Code = UrlParameter.Optional, UserID = UrlParameter.Optional, Password = UrlParameter.Optional }); 

They do not seem to work. Where am I wrong or is this possible? I was able to do this in the RC version of WebApi with MVC3.

+7
source share
2 answers

There seems to be no action in your request ( /api/Login/KeyValue/CodeValue/UserValue/PasswordValue ). Try /api/Login/Get/KeyValue/CodeValue/UserValue/PasswordValue instead if you intend to use the first route.

If you want to be able to call it without the specified action, and the default is Get, you must specify the default action:

 defaults: new { Key = UrlParameter.Optional, Code = UrlParameter.Optional, UserID = UrlParameter.Optional, Password = UrlParameter.Optional, Action = "Get" } 

I have successfully tried this in an ASP.NET MVC 4 project (Visual Studio 2012 RC):

Create a LoginController with action:

 public string Get(string Key, string Code, string UserID, string Password) { return Key + Code + UserID + Password; } 

And the route display in Global.asax.cs:

  RouteTable.Routes.MapHttpRoute(null, "api/{controller}/{Key}/{Code}/{UserID}/{Password}", new { Key = UrlParameter.Optional, Code = UrlParameter.Optional, UserID = UrlParameter.Optional, Password = UrlParameter.Optional, Action = "Get"}); 

If it does not work for you, perhaps another route will catch the request or the route will not be registered.

+10
source

You are trying to do routing without action. He works.

But in this case, you must use the attribute in the controller to indicate the methods of action. You can use the following attributes: HttpGet, HttpPut, HttpPost, HttpDelete, AcceptVerbs, NonAction.

Read more about this in the article:

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

0
source

All Articles