ASP.NET Web API 中的自定义方法名称 [英] Custom method names in ASP.NET Web API

查看:27
本文介绍了ASP.NET Web API 中的自定义方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 WCF Web API 转换为新的 ASP.NET MVC 4 Web API.我有一个 UsersController,我想要一个名为 Authenticate 的方法.我看到了如何执行 GetAll、GetOne、Post 和 Delete 的示例,但是如果我想在这些服务中添加额外的方法怎么办?例如,我的 UsersService 应该有一个名为 Authenticate 的方法,它们在其中传递用户名和密码,但它不起作用.

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");
    }
}

我可以浏览到 myapi/api/users/,它会调用 GetAll,我可以浏览到 myapi/api/users/1,它会调用 Get,但是如果我调用 myapi/api/users/authenticate?username={0}&password={1} 然后它会调用 Get (NOT Authenticate) 并出错:

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:

参数字典包含一个不可为空类型System.Int32"的参数id"的空条目,用于Navtrak.Services.WCF.NavtrakAPI.Controllers.UsersController"中的方法System.String Get(Int32)".可选参数必须是引用类型、可为空类型或声明为可选参数.

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 等自定义方法名称?

How can I call custom method names such as Authenticate?

推荐答案

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

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.

如果你想拥有与标准不同的动作名称,你可以在 global.asax 中修改你的路由定义:

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 }
);

现在您可以导航到 /api/users/getauthenticate 对用户进行身份验证.

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

这篇关于ASP.NET Web API 中的自定义方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆