c# - ASP.NET Web API 中的自定义方法名称

标签 c# asp.net-web-api asp.net-web-api-routing

我正在从 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(不验证)和错误:

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.

如何调用自定义方法名称,例如 Authenticate?

最佳答案

默认情况下,路由配置遵循 RESTFul 约定,这意味着它将仅接受 Get、Post、Put 和 Delete 操作名称(查看 global.asax 中的路由 => 默认情况下,它不允许您指定任何操作name => 它使用 HTTP 动词来调度)。因此,当您向 /api/users/authenticate 发送 GET 请求时,您基本上是在调用 Get(int id) 操作并传递 id=authenticate 这显然会崩溃,因为您的 Get 操作需要一个整数。

如果你想使用不同于标准名称的 Action 名称,你可以在 global.asax 中修改你的路由定义:

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

现在您可以导航到 /api/users/getauthenticate 来验证用户。

关于c# - ASP.NET Web API 中的自定义方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9569270/

相关文章:

c# - Web API Controller 中的多个 HttpPost 方法

c# - 运行 WebAPI 的路径

c# - JSON 值无法转换为 System.Int32

c# - 网络核心/身份服务器: unable to logout

c# - 处理预期的异常

javascript - Ajax 调用认为数据包含 [ ],而数据应该为空

c# - ASP.NET 网站调试速度极慢,有数千个临时 ASP.NET 文件

c# - ASP.NET MVC5 WebAPI2 防止未经授权重定向到登录页面

c# - Web API Controller 的构造函数是如何调用的?