c# - Angular Post json to .net core web api 为空

标签 c# angular asp.net-core asp.net-core-webapi

我正在尝试将一些 JSON 发布到 web api .net 核心,但出于某种原因,无论我尝试了什么,这始终为空,请参见下面的代码。

这是我的 .net 核心 web 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 发布的方式(请注意已加载适当的服务)

    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());
        });
    });
  }

我已经尝试将帖子更改为

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

甚至

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

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

UPDATE 1 如果可能需要解释 好吧,我想做一个小实验,相同的代码适用于 4.5 框架而不是 .net 核心,但是我尝试为 .net 核心做的是创建一个名为 foo 的类,见下文

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

并修改我的 Controller 以接受这个对象

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

还有我的Angular project to pass a similar format 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());
    });
});

这设法成功通过并绑定(bind)到 Controller enter image description here

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

最佳答案

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

string issue received on the API is always null

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

绑定(bind)到模型(viewmodel)

当您的参数是一个类时,asp 会将此类绑定(bind)到您传递的 json 数据,这就是为什么您能够获取 name 数据的原因。 根据您的更新,您可能会走这条路。

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

现在您可能想知道,当参数只是一个字符串时,您为什么要创建一个仅用于您的 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());
        });
    });
  }

希望这对您有所帮助。

关于c# - Angular Post json to .net core web api 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45719017/

相关文章:

c# - Caliburn.Micro - ShowDialog() 如何关闭对话框?

c# - 为隐式转换启用编译器警告 (C#)

c# - 修改后的请求路径上的 HttpContext GetEndpoint .net 5

javascript - 获取外键表数据

asp.net-core - 在 IIS 中部署 MVC 6 应用程序

c# - Google API - Calendar API 正在运行,但 Gmail API 返回 '' unauthorized_client”

c# - 如何从 DataGridView 保存和检索按钮

css - 在 Angular 2 中使用 md-grid-list 进行响应式设计

angular - LimitToFirst AngularFire Observable<any>

angular - 当 ngModel 在没有用户输入的情况下从组件更改时,ngModelChange 不会触发