Angular - 使用PUT时出现400错误(错误请求)

时间:2017-06-22 12:31:34

标签: c# angular

在我的Angular计划中,我试图将用户从我的表中输入的行发布到我的数据库中。但是,无论何时我使用put,在控制台中,我都会收到错误消息

PUT 400 (Bad Request)

我从服务器获得的响应是​​

{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult PutPTOData(Int32, PTOTracker.Models.PTOData)' in 'PTOTracker.Controllers.PTODataController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}

它说我没有输入身份证,但我以为我是。

这是我的模特:

namespace PTOTracker.Models
{
public class PTOData
{
[Key]
public int ID { get; set; }
public int EmpKey { get; set; }
public string type { get; set; }
public DateTime date { get; set; }
public string fullhalf { get; set; }
public int hours { get; set; }
public string scheduled { get; set; }
public string notes { get; set; }
public bool inPR { get; set; }
public DateTime? prDate { get; set; }

}   }

这是我的组件中的保存功能:

    saveNewRow(): void {
    this.ptoDataService.save(this.newRow)
        .then(PTOData => {
            this.ptoData.push({
                ID: 123456,
                EmpKey: this.empInfo[this.selectedEmployee].EmpKey,
                type: this.selectedType,
                date: this.newRow.date,
                fullhalf: this.newRow.fullhalf,
                hours: this.newRow.hours,
                scheduled: this.newRow.scheduled,
                notes: this.newRow.notes,
                inPR: (this.newRow.inPR ? true : false),
                prDate: this.newRow.prDate
            })
        })

   }

这是我服务中的保存功能:

    save(pto: PTOData): Promise<PTOData> {
    return this.http
        .put(this.ptoDateUrl + '/' + pto.ID, pto, this.options)
        .toPromise()
        .then(res => res.json().data as PTOData)
        .catch(this.handleError);
}

这是我的PTODataController:

&#13;
&#13;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using PTOTracker.Models;

namespace PTOTracker.Controllers
{
    public class PTODataController : ApiController
    {
        private PTOTrackerContext db = new PTOTrackerContext();

        // GET: api/PTOData
        public IQueryable<PTOData> GetPTODatas()
        {
            return db.PTODatas;
        }

        // GET: api/PTOData/5
        [ResponseType(typeof(PTOData))]
        public IHttpActionResult GetPTOData(int id)
        {
            PTOData pTOData = db.PTODatas.Find(id);
            if (pTOData == null)
            {
                return NotFound();
            }

            return Ok(pTOData);
        }

      // PUT: api/PTOData/5
      [HttpPut]
      [ResponseType(typeof(void))]
      [Route("api/PTOData/{id}")]
        public IHttpActionResult PutPTOData(int id, PTOData pTOData)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != pTOData.ID)
            {
                return BadRequest();
            }

            db.Entry(pTOData).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PTODataExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/PTOData
        [ResponseType(typeof(PTOData))]
        public IHttpActionResult PostPTOData(PTOData pTOData)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.PTODatas.Add(pTOData);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = pTOData.ID }, pTOData);
        }

        // DELETE: api/PTOData/5
        [ResponseType(typeof(PTOData))]
        public IHttpActionResult DeletePTOData(int id)
        {
            PTOData pTOData = db.PTODatas.Find(id);
            if (pTOData == null)
            {
                return NotFound();
            }

            db.PTODatas.Remove(pTOData);
            db.SaveChanges();

            return Ok(pTOData);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool PTODataExists(int id)
        {
            return db.PTODatas.Count(e => e.ID == id) > 0;
        }
    }
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

问题似乎是这样:

saveNewRow(): void {
this.ptoDataService.save(this.newRow)
    .then(PTOData => {
        this.ptoData.push({
            ID: 123456,
            EmpKey: this.empInfo[this.selectedEmployee].EmpKey,
            type: this.selectedType,
            date: this.newRow.date,
            fullhalf: this.newRow.fullhalf,
            hours: this.newRow.hours,
            scheduled: this.newRow.scheduled,
            notes: this.newRow.notes,
            inPR: (this.newRow.inPR ? true : false),
            prDate: this.newRow.prDate
        })
    })

}

您在提出请求后推送新对象,而不是之前。 应该是这样的:

this.ptoDataService.save({
                ID: 123456,
                EmpKey: this.empInfo[this.selectedEmployee].EmpKey,
                type: this.selectedType,
                date: this.newRow.date,
                fullhalf: this.newRow.fullhalf,
                hours: this.newRow.hours,
                scheduled: this.newRow.scheduled,
                notes: this.newRow.notes,
                inPR: (this.newRow.inPR ? true : false),
                prDate: this.newRow.prDate})
    .then((response: any) => { //do what you want with the response.})

答案 1 :(得分:1)

将记录添加到数据库的代码不正确。

首先,按照camaron的解决方案改变JS方面。

然后在服务器端,您需要将实体添加到数据库中。 https://stackoverflow.com/a/22222636/34092有很好的样本。

db.Entry(pTOData).State = EntityState.Modified;

需要更改为:

db.PTODatas.Add(pTOData);

return StatusCode(HttpStatusCode.NoContent);

需要更改为:

return Ok(pTOData);