【问题标题】:How can ModelState be accessed in HttpPut if it is only created in HttpPost?ModelState 如果只在 HttpPost 中创建,如何在 HttpPut 中访问?
【发布时间】: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


    【解决方案1】:

    这是一个不完整且有些混乱的定义。模型只是您发送数据的方式,仅此而已。它可以通过 GET、POST、PUT 等等。它只是对每个端点需要的任何数据进行建模,仅此而已。

    我猜提到 POST 是因为这是最常见的场景,但不要让它限制您对它的理解。

    PUT 和 POST 的模型可能相同,或者它们可能会有些不同。 例如,您的实体模型可能包含也可能不包含 ID。创建数据的 POST 不需要 ID,而 PUT 需要。

    如果您用于更新的模型已经包含 ID,那么您可能决定不将 ID 分开,因为它是冗余数据。所以你看,你需要使用 API 做出许多决定。

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多