【问题标题】:Sending Multiple Objects from Angular 8 to .Net Core Web Api - Null at Controller End [closed]将多个对象从 Angular 8 发送到 .Net Core Web Api - 控制器端为 Null [关闭]
【发布时间】:2020-11-19 08:26:40
【问题描述】:

我有以下方法将多个对象发送到 .Net Core Web API

 this.http.post('api/InternalReport/create', [
              this.internalreport,
              this.file]
            , { observe: 'response', responseType: 'text' }).subscribe(data => {
                if (data.status == 200) { console.log("success");}
              }, err => { console.error('Observer got an error:');});

API 控制器

[HttpPost("create")]
        public ActionResult<InternalReport> Create([FromBody]InternalReport report,[FromBody]File file)
        {
            try
            {
                _internalreportService.Create(report);
                _fileservice.Update(file.sha1,file);
                return Ok("success");
            }
            catch (Exception e)
            {
                return NotFound();
            }



        }

但是在控制器端这两个对象都是空的。

【问题讨论】:

    标签: c# typescript angular8 asp.net-core-webapi


    【解决方案1】:

    使用JsonType,你只能传递一个对象,如果你想传递多个对象,你需要创建一个包含多个对象的新对象。 这是一个演示:

    角度数据:

    public class AngularData
        {
            public Student student { get; set; }
            public string a { get; set; }
    
        }
    

    学生:

    public class Student
        {
            public string Gender { get; set; }
        }
    

    发送数据:

    SendData() {
      var student={'Gender':'male'};
      var angulardata={student,'a':'aaa'}
       const headers = new HttpHeaders().set('Content-Type','application/json');
       this.http.post('https://localhost:44363/create',JSON.stringify(angulardata),{headers:headers})
    .subscribe(data => {
    });
    

    控制器:

    [HttpPost("create")]
            public IActionResult  Create([FromBody]AngularData angularData)
            {
                return Ok();
    
    
    
            }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2015-05-03
      • 2017-05-17
      • 2023-02-04
      • 1970-01-01
      • 2021-02-07
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      相关资源
      最近更新 更多