gpt4 book ai didi

c# - WebAPI POST 方法抛出空异常

转载 作者:行者123 更新时间:2023-11-30 23:21:34 25 4
gpt4 key购买 nike

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

{"Value cannot be null.\r\nParameter name: entity"} on line 84, db.Reviews.Add(review)

我正在使用 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);

评论 Controller

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; }
}
}

猎豹实体

//------------------------------------------------------------------------------
// <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; }
}
}

最佳答案

在请求中,您的内容类型为 application/json,但发送您的 params 时带有 ReviewId=123,这不是 json。如果您将 Content-Type 作为 application/json 发送,params 应该是正确格式化的 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 方法中,如果 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);
}

关于c# - WebAPI POST 方法抛出空异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com