WEB.API 不会反序列化 POST 方法中传入的 JSON

Mik*_*hev 2 c# .net-core asp.net-core angular

我基于.Net-Core创建了Web.Api。有两种方法:

  1. IEnumerable GetRoles() -(获取)
  2. ResponseObject GetUsers(PagerRequest pagerRequest ) - (发布)。它具有以下属性: [Route("api/users/getusers")] [HttpPost]

这两种方法都由 Angular 调用。方法 GetRoles 正在工作,但问题出在 POST 中。

PagerRequest 是一个简单的类,它有一些 int 属性。它是由 Angular 填充的。Fiddler 显示正确的 JSON:

POST http://localhost/Pir.API/api/users/getusers HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 84
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
content-type: application/json
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7

{
  "CountButtons": 5,
  "ItemsCount": 0,
  "PageSize": 5,
  "CurrentPageIndex": 0
}
Run Code Online (Sandbox Code Playgroud)

GetUsers 方法正在调用,但输入参数未初始化。换句话说,反串行化不起作用,我不明白为什么。

之前这个项目是基于经典的.Net并在IIS中运行的。一切正常。但.Net CORE是一个问题。

谁知道问题出在哪里?

下面的代码示例:

-------------- PagerRequest.cs --------------------

public class PagerRequest
{
     public int ItemsCount { get; set; }
     public int PageSize { get; set; }
     public int CurrentPageIndex { get; set; }
     public int CountButtons { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

-------------- PagerRequest.ts --------------------

export class PagerRequest{
    ItemsCount:number;
    PageSize:number;
    CurrentPageIndex:number;
    CountButtons:number;    
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*und 6

您需要告诉框架从请求正文中读取数据。执行此操作FromBody Attribute

[HttpPost]
ResponseObject GetUsers([FromBody]PagerRequest pagerRequest)
Run Code Online (Sandbox Code Playgroud)

注意:如果执行 HttpPost,则名称 GetUsers 会产生误导。一个技巧是改变这一点