【发布时间】:2017-08-26 07:23:28
【问题描述】:
我有一个简单的 Web api,它使用数据库优先的 ADO SQL 服务器实体,其中有一个表,其中有一个自动递增的标识列和一个 nvarchar 列。我的 GET 函数工作正常,但我在使用 POST 时遇到问题。
这是我的控制器,大部分是自动生成的:
public class CustomersController : ApiController
{
private MyEntities db = new MyEntities();
// GET: api/Customers
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
}
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
public IHttpActionResult GetCustomer(int id)
{
Customer customer = db.Customers.FirstOrDefault(x => x.CustomerPk == id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
// PUT: api/Customers/5
[ResponseType(typeof(void))]
public IHttpActionResult PutCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != customer.CustomerPk)
{
return BadRequest();
}
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Customers
[ResponseType(typeof(Customer))]
public IHttpActionResult PostCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Customers.Add(customer);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = customer.CustomerPk }, customer);
}
// DELETE: api/Customers/5
[ResponseType(typeof(Customer))]
public IHttpActionResult DeleteCustomer(int id)
{
Customer customer = db.Customers.FirstOrDefault(x => x.CustomerPk == id);
if (customer == null)
{
return NotFound();
}
db.Customers.Remove(customer);
db.SaveChanges();
return Ok(customer);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool CustomerExists(int id)
{
return db.Customers.Count(e => e.CustomerPk == id) > 0;
}
}
在 HTML 页面中,我调用以下 jquery ajax:
var customer = { "CustomerPk": 0, "CustomerName": "TEST2" };
$.ajax(
{
url: "http://serverurl/site/api/customers",
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(customer),
dataType: "json",
success: function (data, textStatus, xhr) { alert("Success"); },
error: function (xhr, textStatus, errorThrown)
{
var msg = "Code: " + xhr.status + "\n";
msg += "Text: " + xhr.statusText + "\n";
if (xhr.responseJSON != null)
{
msg += "JSON Message: " + xhr.responseJSON.Message + "\n";
}
alert(msg);
}
});
就像我提到的,当我从这个页面调用 GET 方法时,一切正常。我已经尝试了基于无数示例的 ajax 方法的不同变体,这些示例在线将对象发布到 web api,主要是更改我发布的对象,省略身份列并仅发送 CustomerName 列,或将 Pk 设置为 null ,但这些都不起作用。我总是收到 500 内部服务器错误。
它不适用于自动递增的标识列吗?我看到的示例似乎没有将它们作为模型的一部分,所以我想知道这是否是我的问题。
任何帮助或建议将不胜感激,谢谢。
【问题讨论】:
标签: jquery ajax asp.net-web-api asp.net-web-api2