我通过Angular 6发布了一些数据,但是我的Core API不断返回空值:
请求:
{"id":0,"name":"test","weight":2,"frequency":2,"activityTypeModelId":3}
响应:
{id: 0, name: null, weight: 0, frequency: 0, activityTypeModelId: 0}
控制器:
[HttpPost("[action]")]
public IActionResult Add([FromForm]Model model)
{
return new JsonResult(model);
}
Angular,使用HttpClient:
add(Model: model) {
return this.http.post(this.addUrl, model);
}
API模型:
public class Model
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Weight { get; set; }
public int Frequency { get; set; }
public int ActivityTypeModelId { get; set; }
}
TS型号:
export class Model{
id?: number;
name?: string;
weight?: number;
frequency?: number;
activityTypeModelId?: number;
}
当我使用Postman时,一切正常。我已经尝试了[FromBody]。问题出在哪儿?
我不知道为什么,但这解决了我的问题:
我创建了一个标题:
const header = new HttpHeaders()
.set('Content-type', 'application/json');
通过添加标头和JSON.Stringify对象来更改POST功能:
add(model: Model): Observable<Model> {
const body = JSON.stringify(c);
return this.http.post<Model>(this.addUrl, body, { headers: header} );
}
将[FromForm]
改为[FromBody]
。
在JSON.stringify(model)
的参数中添加http.post
不起作用。
使用CORE Api的JSON:
{"name":"test","weight":2,"activityTypeModelId":15}
不使用CORE Api的JSON:
{name:"test",weight:2,activityTypeModelId:15}
没有标题我从API遇到415错误。
尝试
return this.http.post(this.addUrl, JSON.stringify(model) );
我认为,在.NET Core 2.1中(参见https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.1)
HttpPost("[action]")]
//see that I put [FromBody]
public IActionResult Add([FromBody]Model model)
{
//OK is one of several IActionResult
return OK(model);
}