2017-08-28 42 views
0

我的视图模型或DTO总是在我的服务器端的空当我把它例如我把方法视图模型我总是在服务器端零(角2 + ASP.NET核心)

这里是我的客户端的方法

update(company: Company) { 
return this.apiService.put(`${this.path}/${company.id}`, 
company); 
} 

Put method in apiService 

put(path: string, body): Observable<any> { 
    debugger; 
    this.setBearerHeader(); 
    console.log('Http Post Observable: ', path, body); 
    let url = `${this.baseUrl}${path}`; 
    let request = new Request({ 
     url: url, 
     headers: this.headers, 
     method: RequestMethod.Put, 
     body: body 
    }); 

    return this.http.request(request) 
     .catch(this.handleError) 
     .map(res => res.json()) 
}; 

而我的服务器端模型在我的dto总是为空。是否总是需要使用[FromBody]?

[HttpPut("{id}")] 
public async Task<IActionResult> Put(string id,ViewModel dto) 
{ 
    if (!ModelState.IsValid) 
    { 
    return BadRequest(ModelState); 
    } 

    try 
    { 
    if (id != dto.Id) 
    { 
     return BadRequest(); 
    } 
    } 
    catch (Exception ex) 
    { 
    throw; 
    } 
} 

回答

2

dto参数需要[FromBody]属性。

[HttpPut("{id}")] 
public async Task<IActionResult> Put(string id, [FromBody]ViewModel dto) 
{ 
    // ... 
} 
+0

好吧,也许你能帮助我在我的另一个问题https://stackoverflow.com/questions/45919932/upload-model-with-iformfile-propertis-from-angular2-to-asp-net-core- webapi – Stefan

+0

而且我想问问是否有办法不使用FromBody? – Stefan

+1

可能用自定义的'IModelMetadataProvider'覆盖'BindingSource'。你有什么令人信服的理由来做到这一点? –