【发布时间】:2020-12-31 23:43:11
【问题描述】:
“ModelState 表示在 POST 期间提交给服务器的名称和值对的集合。”这是我为 ModelState 属性找到的最佳定义。所以我有一些使用创建客户和更新客户的 web api 的代码,我的问题是,因为我已经在 CreateCustomer 中访问了 ModelState,如果我还没有使用 CreateCustomer 提交 Post 请求,ModelState 是否总是无效?或者 ModelState 是否同时使用 PUT 和 Post 请求进行了更新?因为根据上面的定义,ModelState 属性在我创建客户之前不会被初始化,并且在我的 UpdateCustomer 方法中,我需要检查参数中给出的客户对象是否是有效的,而不是任何提交的模型在不同的 POST 请求期间发送到服务器。
[HttpPost]
//If we name it PostCustomer, we dont have to put the httppost tag
public Customer CreateCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
_context.Customers.Add(customer);
_context.SaveChanges();
return customer;
}
// Put /api/customers/1
[HttpPut]
public void UpdateCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
Customer customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customerInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
customerInDb.Name = customer.Name;
customerInDb.Birthdate = customer.Birthdate;
customerInDb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
customerInDb.MembershipTypeId = customer.MembershipTypeId;
_context.SaveChanges();
}
代码来自 Mosh Hamedani 的 ASP.Net MVC 课程。 链接到 ModelState 定义。 https://exceptionnotfound.net/asp-net-mvc-demystified-modelstate/
【问题讨论】:
标签: c# asp.net asp.net-mvc api asp.net-web-api