【问题标题】:Posted object with collection does not get bound to http body content带有集合的已发布对象未绑定到 http 正文内容
【发布时间】:2016-10-08 22:15:03
【问题描述】:

我正在向服务器发送一个带有 PupilsScores 列表的对象的 http put 方法。

TestId 已绑定,但 PupilsScores 集合为空。

我也尝试过[FromBody],但这应该是我假设的默认设置。

那么为什么我的 PupilsScores 集合为空?

客户

     updateTestAssignment(pupilsScores, testId) {
   return this.http.put('/api/testassignments/' + testId, { pupilsScores: pupilsScores }).map(res => res.json());
      }

服务器

public class UpdateTestAssignmentRequestDto
{
    public int TestId { get; set; }

    public IEnumerable<PupilsScoresRequestDto> PupilsScores { get; set; }
}

[HttpPut("~/api/testassignments/{testId:int}")]
public async Task<IActionResult> Put(UpdateTestAssignmentRequestDto dto)
{

    return NoContent();
}

【问题讨论】:

    标签: c# angular asp.net-core


    【解决方案1】:

    您还需要指定Content-Type。它的默认值为text/plain

    import { Headers, RequestOptions } from '@angular/http';
    
    let headers = new Headers({ 'Content-Type': 'application/json' }); // for ASP.NET MVC
    let options = new RequestOptions({ headers: headers });
    
    this.http.post(url, JSON.stringify(product), options).map(....)
    

    【讨论】:

    • 您确定 RequestOptions 吗? => stackoverflow.com/questions/37595980/… ,无论如何我都尝试了这两个选项,但它不起作用。当 content-type 为 json 时,最后一个 Angular 2 版本不再需要 JSON stringify。
    • 好的,明确设置 [FromBody] 并且没有 json.stringify 和没有 RequestOptions 但遵循此链接:stackoverflow.com/questions/37595980/… 使其最终工作。我还必须再次将路由中的 TestId 放入有效负载中以与 FromBody 绑定。
    • 我现在也使用 RequestOptions 对其进行了测试,它也可以正常工作。因此,请更改您的答案,包括我的发现服务器/客户端 :-) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多