WebAPI未找到

Jef*_*eff 3 asp.net-mvc asp.net-mvc-4 asp.net-web-api

可悲的是,我无法获得使用WebAPI的最基本的东西

$.ajax({
    url: "https://192.168.1.100/Api/Authentication/LogIn",
    type: "POST",
    contentType: "application/json",
    data: "{ 'username': 'admin', 'password': 'MyPass' }",
    error: function (r, s, e) { alert(e); },
    success: function (d, s, r) { alert(s); }
});
Run Code Online (Sandbox Code Playgroud)

我得到"未找到"

API控制器定义

public class AuthenticationController : ApiController
{
    [HttpPost]
    public bool LogIn(string username, string password)
    {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我删除HttpPost并将其替换为HttpGet然后执行

$.ajax({
    url: "https://192.168.1.100/Api/Authentication/LogIn?username=admin&password=MyPass",
    type: "GET",
    error: function (r, s, e) { alert(e); },
    success: function (d, s, r) { alert(s); }
});
Run Code Online (Sandbox Code Playgroud)

这很好.

WebAPI出了什么问题?

Jim*_*itt 6

本文应该有助于回答您的一些问题.

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

我相信这里的想法是,特别是在RESTful API中,您需要将数据绑定到特定方法处理的单个资源.因此,将数据推送到几个松散的参数并不是Web API所需要的那种用法.

处理发布数据时,您可以告诉您的操作方法正确绑定其参数,如下所示:

public class LoginDto {
    public string Username { get; set; }
    public string Password { get; set; }
}

[HttpPost]
public bool LogIn(LoginDto login) {
    // authenticate, etc
    return true;
}
Run Code Online (Sandbox Code Playgroud)