Angular Post json to .net core web api 为空

Angular Post json to .net core web api is null

我正在尝试 post 一些 JSON 到网络 api .net 核心,但出于某种原因,无论我尝试了什么,这总是空的,请参见下面的代码。

这是我的 .net 核心网站 api 代码

    [Produces("application/json")]
    [Route("api/v1/Issues")]
    [Authorize]
    [EnableCors("AllowCors")]
    public class IssuesController : Controller
    {
        [HttpPost]
        public IActionResult PostIssues([FromBody] string issue)
        {
          //some code to desirialize
        }
    }

这就是我尝试通过 angular post 的方式(请注意已加载适当的服务)

    public addIssue(issue) {
    const headers = new Headers();
    this.authService.getToken().toPromise().then( t => {
      headers.append('Authorization', `Bearer ${t.toString()}`);
      headers.append('Content-Type', 'application/json')
      this.http.post(`${this.baseUrl}/v1/issues`, issue, {
        headers: headers
      }).toPromise()
        .then(res => {
          console.log(res.json());
        });
    });
  }

我试过将 post 更改为

this.http.post(`${this.baseUrl}/v1/issues`, JSON.stringify(issue))

甚至

this.http.post(`${this.baseUrl}/v1/issues`, {'issue', JSON.stringify(issue)})

但似乎没有任何效果有人知道为什么会这样吗? 澄清在 API 上收到的 string issue 始终为空。 这是当我到达服务器时的成功响应,您可以看到请求负载不为空,但到达网络 api 为空

更新 1 如果可能需要解释 好吧,我想做一个小实验,相同的代码在 4.5 框架而不是 .net 核心上运行良好,但是我尝试为 .net 核心做的是创建一个名为 foo 的 class,见下文 [=24] =]

public class Foo
    {
        public string Name { get; set; }
        public string Json { get; set; }
    }

并修改我的控制器以接受这个对象

   [HttpPost]
    public IActionResult PostIssues([FromBody] Foo issue)
    {
       Debug.Write(issue);
       return Ok(issue);
    }

还有我的Angular项目要传一个类似格式的body

public addIssue(issue) {
const headers = new Headers();
this.authService.getToken().toPromise().then( t => {

  headers.append('Authorization', `Bearer ${t.toString()}`);
  headers.append('Content-Type', 'application/json');

  this.http.post(`${this.baseUrl}/v1/issues`, {'name' : 'name', 'json': JSON.stringify(issue)}, {
    headers: headers,
    withCredentials: true
  }).toPromise()
    .then(res => {
      console.log(res.json());
    });
});

}

这成功通过并绑定到控制器

为什么这个可以,但是不能直接传一个Json?为什么我的原始代码适用于 4.5 框架而不适用于 .net 核心?

因为它是单个字符串,所以您可以在 url

中传递它
${this.baseUrl}/v1/issues?issue=yourVarIssue

我会尽量回答你所有的问题。

string issue received on the API is always null

将 JSON 传递给它总是会得到一个空值,因为您正试图绑定到原始数​​据类型。要解决此问题,您有两种选择

绑定到模型 (viewmodel)

当您的参数是 class 时,asp 会将此 class 绑定到您传递的 json 数据,这就是为什么您能够获得 name 数据。 根据您的更新,您可能会走这条路。

更多信息:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

现在你可能想知道为什么你会创建一个 class 只是为了在你的 api 上使用,而参数只是一个字符串?!如果你只想在你的 api 中使用 string 那么你可以这样做

使用FormData

传递数据

你需要像这样改变你的api

 public IActionResult PostIssues(string issue){..}

这里不需要指定[FromBody]

在您的客户端,

 public addIssue(issue) {
    const headers = new Headers();
    this.authService.getToken().toPromise().then( t => {
      headers.append('Authorization', `Bearer ${t.toString()}`);
     // new code here
    var formData = new FormData();
    formData.append('issue',issue); //you need to specify the parameter name here.
      this.http.post(`${this.baseUrl}/v1/issues`, formData, {
        headers: headers
      }).toPromise()
        .then(res => {
          console.log(res.json());
        });
    });
  }

希望对您有所帮助。