0
当我做一个职位,我得到的错误POST http://localhost:5000/api/activities 400(错误请求) 但是当我添加一个ID我放完美的作品。angular2“400错误的请求”在POST请求
有人可以帮我,我没有找到解决办法。为什么我会收到400(错误请求)错误?
这里是我的代码:
全球:
BASE_URL_API = 'http://localhost:5000/api/'
在activitiy.service.ts
private activitiesUrl = this.globals.BASE_URL_API + 'activities';
//POST
private post(activity: Activity): Promise<Activity> {
let headers = new Headers({
'Content-Type': 'application/json'
});
return this.http
.post(this.activitiesUrl, JSON.stringify(activity), { headers: headers })
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
// Update existing Activity
private put(activity: Activity): Promise<Activity> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let url = `${this.activitiesUrl}/${activity.id}`;
return this.http
.put(url, JSON.stringify(activity), { headers: headers })
.toPromise()
.then(() => activity)
.catch(this.handleError);
}
在addActivity.ts
activityCredentials = {
id: null,
name: 'test',
description: 'test description',
locationId: 2,
activityTypeId: 2,
};
...
public save(){
this.activityService.save(this.activityCredentials).then(success => {
if (success) {
this.createSuccess = true;
this.showPopup("Success", "Activity added.");
} else {
this.showPopup("Error", "Problem adding activities.");
}
},
error => {
this.showPopup("Error", error);
});
}
在ASP
。 NET API
[HttpPost(Name = "CreateActivity")]
public async Task<IActionResult> CreateActivity([FromBody] Activity item)
{
if(item == null)
{
return BadRequest();
}
ApplicationDbContext.Activities.Add(item);
await ApplicationDbContext.SaveChangesAsync();
return this.CreatedAtRoute("GetActivityById", new { Controller = "ActivitiesController", activityId = item.Id }, item);
}
[HttpPut("{activityId:int}", Name = "UpdateActivity")]
public async Task<IActionResult> UpdateActivity(Int16 activityId, [FromBody] Activity item)
{
if(item == null || item.Id != activityId)
{
return BadRequest();
}
var model = await ApplicationDbContext.Activities.FirstOrDefaultAsync(o => o.Id == activityId);
if(model == null)
{
var msg = String.Format(FAILGETENTITYBYID, activityId);
return NotFound(msg);
}
model.Name = item.Name;
model.Description = item.Description;
model.LocationId = item.LocationId;
model.ActivityTypeId = item.ActivityTypeId;
ApplicationDbContext.Activities.Attach(model);
ApplicationDbContext.Entry(model).State = EntityState.Modified;
await ApplicationDbContext.SaveChangesAsync();
return new NoContentResult();
}
我不明白为什么。有人可以帮我吗?
检查JSON.stringify(activity)对象是否传递param's – Vignesh
@Vignesh JSON.stringify(activity)正在传递param's –
您在发送小写'is',而在服务器上访问'Id'时大写字母i。请检查是否是这个问题。 –