Angular post 请求 c# web api 2 RESTful web 服务

Angular post request to c# web api 2 RESTful web service

我正在尝试从 angular 客户端向 C# web API 2 RESTful web 服务发送一个 http post 请求。

我的客户:

var userId = "123456";
var password = "654321";

const headersContent = new Headers().set('Content-Type', 'application/x-www-form-urlencoded');
var url = "http://localhost:35615/login"
this.http.post(url, {
    "userId": userId,
    "password": password
}, {withCredentials: true}).subscribe(res => {
    console.log(res);
});

我的服务器:

[Route("login")]
[HttpPost]
public IHttpActionResult LoginReq([FromBody] string parameters)
{
    //Deserialize the parameters.
}

我的问题是参数 var 为空,尽管 chrome 网络选项卡中的 post 请求包含数据。

谁能解释一下我做错了什么,我该如何解决? 谢谢!

你 post userIdpassword,但期望 String parameters。更改为 String userIdString password。 Modelbinder 只会绑定匹配的属性。

您正在传递一个具有属性 "UserId" 和 "Password" 的匿名对象。 制作一个数据协定 class 将这 2 个属性作为字符串并在 REST 方法的参数中使用它。

public IHttpActionResult LoginReq([FromBody] User user) { ... }

只需添加 JSON.stringify() 您正在向服务器发送一个对象,该对象只需要一个字符串作为参数,因此将其作为一个字符串并传递值,否则使用 useridpassword 在您的服务器端并提及该对象

let obj =  {
        "userId": userId,
        "password": password
    };   
this.http.post(url, JSON.stringify(obj), {withCredentials: true}).subscribe(res => {
        console.log(res);
    });

以上代码将与 string parameters 一起使用 - 继续尝试使用模型并从 Angular

传递对象

编码愉快!!

如果您从 Angular POST 请求传递一个对象,可以更改 Web API POST 方法以接受用户定义的类型作为要读取的参数它来自请求正文。

您可以在 C# 中创建以下用户定义的类型,以从您的 angular Post 请求

中绑定 UserId 和 Password 属性
public class UserLogin
{
    public int UserId { get; set; }
    public string Password { get; set; }
}

[Route("login")]
[HttpPost]
public IHttpActionResult LoginReq([FromBody] UserLogin user)
{
    //Deserialize the parameters.
}

我建议通过此 documentation 阅读更多关于 Web 中参数绑定的信息 API。相信我,这值得你花时间。