Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom method names in ASP.NET Web API

I'm converting from the WCF Web API to the new ASP.NET MVC 4 Web API. I have a UsersController, and I want to have a method named Authenticate. I see examples of how to do GetAll, GetOne, Post, and Delete, however what if I want to add extra methods into these services? For instance, my UsersService should have a method called Authenticate where they pass in a username and password, however it doesn't work.

public class UsersController : BaseApiController {     public string GetAll()     {         return "getall!";     }      public string Get(int id)     {         return "get 1! " + id;     }      public User GetAuthenticate(string userName, string password, string applicationName)     {         LogWriter.Write(String.Format("Received authenticate request for username {0} and password {1} and application {2}",             userName, password, applicationName));          //check if valid leapfrog login.         var decodedUsername = userName.Replace("%40", "@");         var encodedPassword = password.Length > 0 ? Utility.HashString(password) : String.Empty;         var leapFrogUsers = LeapFrogUserData.FindAll(decodedUsername, encodedPassword);          if (leapFrogUsers.Count > 0)         {             return new User             {                 Id = (uint)leapFrogUsers[0].Id,                 Guid = leapFrogUsers[0].Guid             };         }         else             throw new HttpResponseException("Invalid login credentials");     } } 

I can browse to myapi/api/users/ and it will call GetAll and I can browse to myapi/api/users/1 and it will call Get, however if I call myapi/api/users/authenticate?username={0}&password={1} then it will call Get (NOT Authenticate) and error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'Navtrak.Services.WCF.NavtrakAPI.Controllers.UsersController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

How can I call custom method names such as Authenticate?

like image 541
Justin Avatar asked Mar 05 '12 15:03

Justin


People also ask

How do you provide an alias name for an action method in Web API?

An alias name for an action method is provided by using ActionName attribute. Also it is necessary to change the route template in the WebApiConfig. cs.

What is action name in Web API?

To find the action, Web API looks at the HTTP verb, and then looks for an action whose name begins with that HTTP verb name. For example, with a GET request, Web API looks for an action prefixed with "Get", such as "GetContact" or "GetAllContacts".


1 Answers

By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate you are basically calling the Get(int id) action and passing id=authenticate which obviously crashes because your Get action expects an integer.

If you want to have different action names than the standard ones you could modify your route definition in global.asax:

Routes.MapHttpRoute(     name: "DefaultApi",     routeTemplate: "api/{controller}/{action}/{id}",     defaults: new { action = "get", id = RouteParameter.Optional } ); 

Now you can navigate to /api/users/getauthenticate to authenticate the user.

like image 151
Darin Dimitrov Avatar answered Sep 21 '22 21:09

Darin Dimitrov