WebAPI POST方法抛出null异常

时间:2016-08-26 00:01:52

标签: c# asp.net-web-api

我创建了一个WebAPI项目,在使用DELETE和GET方法时工作正常,但是当我尝试POST或PUT时,我收到了

  

{"值不能为空。\ r \ n参数名称:实体"}在第84行,   db.Reviews.Add(综述)

我正在使用Postman进行测试,我也尝试使用XMLHttpRequest,但这两种方法都可以在GET / DELETE上运行,在PUT / POST时失败。

var update1 = new XMLHttpRequest();
var params = "ReviewID=123";
update1.open("POST", "http://localhost:49681/Api/Reviews/", true);
update1.setRequestHeader("Content-type", "application/json");
update1.send(params);

ReviewsController

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.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using ReviewApp.Models;

namespace ReviewApp.Controllers
{
    public class ReviewsController : ApiController
    {
        private CheetahEntities db = new CheetahEntities();

        // GET: api/Reviews
        public IQueryable<Review> GetReviews()
        {
            return db.Reviews;
        }

        // GET: api/Reviews/5
        [ResponseType(typeof(Review))]
        public async Task<IHttpActionResult> GetReview(string id)
        {
            Review review = await db.Reviews.FindAsync(id);
            if (review == null)
            {
                return NotFound();
            }

            return Ok(review);
        }

        // PUT: api/Reviews/5
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> PutReview(string id, Review review)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != review.ReviewID)
            {
                return BadRequest();
            }

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

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ReviewExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Reviews
        [ResponseType(typeof(Review))]
        public async Task<IHttpActionResult> PostReview(Review review)
        {
            /*
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            */
            db.Reviews.Add(review);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ReviewExists(review.ReviewID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = review.ReviewID }, review);
        }

        // DELETE: api/Reviews/5
        [ResponseType(typeof(Review))]
        public async Task<IHttpActionResult> DeleteReview(string id)
        {
            Review review = await db.Reviews.FindAsync(id);
            if (review == null)
            {
                return NotFound();
            }

            db.Reviews.Remove(review);
            await db.SaveChangesAsync();

            return Ok(review);
        }

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

        private bool ReviewExists(string id)
        {
            return db.Reviews.Count(e => e.ReviewID == id) > 0;
        }
    }
}

评分

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ReviewApp.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Review
    {
        public string ReviewID { get; set; }
        public string ReviewStatus { get; set; }
        public Nullable<System.DateTime> Date { get; set; }
        public string Account { get; set; }
    }
}

CheetahEntities

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ReviewApp.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class CheetahEntities : DbContext
    {
        public CheetahEntities()
            : base("name=CheetahEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Review> Reviews { get; set; }
    }
}

1 个答案:

答案 0 :(得分:2)

在请求中,您将内容类型设为application/json,但将params发送给不是json的ReviewId=123。如果您将params作为Content-Type发送,application/json应该是格式正确的JSON对象。

var update1 = new XMLHttpRequest();
var params = JSON.stringify({ ReviewID : 123 }); //JSON payload
update1.open("POST", "http://localhost:49681/Api/Reviews/", true);
update1.setRequestHeader("Content-type", "application/json");
update1.send(params);

PostReview方法中,review变量有可能null变量POST如果// POST: api/Reviews [ResponseType(typeof(Review))] public async Task<IHttpActionResult> PostReview(Review review) { if (review == null) ModelState.AddModelError("", "invalid data"); if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Reviews.Add(review); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (ReviewExists(review.ReviewID)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = review.ReviewID }, review); } 请求未正确发送,但之前没有检查变量试图将其添加到数据库。您注释了模型的验证检查。

__repr__