asp.net-mvc - 未找到 WebAPI

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

我得到“未找到”

API Controller 定义

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

如果我删除 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); }
});

效果很好。

WebAPI 出了什么问题?

最佳答案

这篇文章应该有助于回答您的一些问题。

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

I believe the thinking here is that, especially in a RESTful API, you’ll want to bind data to the single resource that a particular method deals with. So, pushing data into several loose parameters isn’t the sort of usage that Web API caters to.

在处理发布数据时,您可以像这样告诉您的操作方法正确绑定(bind)其参数:

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

[HttpPost]
public bool LogIn(LoginDto login) {
    // authenticate, etc
    return true;
}

关于asp.net-mvc - 未找到 WebAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424340/

相关文章:

c# - 从默认路由 C# MVC 中排除 Controller

asp.net-mvc - MVC RequireHttps 整个网站

wcf - 何时使用MVC4 Web-API和传统的HTTP Web服务?

asp.net-mvc - MVC4 Web API 或 MVC3 JsonResult

mysql - 使用 Hangfire 进行自动付款处理

javascript - 如何在更改事件时检索 Kendo MultiSelect For 的发件人 ID?

asp.net-mvc-4 - 从下拉列表中获取选定的值,同时将其与 razor foreach 绑定(bind)

c# - RDLC 矩阵的行号

jquery - 使用 WEB API 的 Ajax Jquery 请求

asp.net-mvc - HttpRequestMessage 内容中的文件名