我正在从WCF Web API转换到新的ASP.NET MVC 4 Web API。我有一个UsersController,并且我想要有一个名为Authenticate的方法。我看到了如何执行GetAll、GetOne、Post和Delete的示例,但是如果我想在这些服务中添加额外的方法怎么办?例如,我的UsersService应该有一个名为Authenticate的方法,他们可以通过用户名和密码进行验证,但它不起作用。
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");
}
}
我可以浏览到myapi/api/users/并调用GetAll,我还可以浏览到myapi/api/users/1并调用Get方法,但是如果我调用myapi/api/users/authenticate?username={0}&password={1},它将调用Get(而不是Authenticate),并显示错误信息:
如何调用自定义方法名称,例如Authenticate?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.