簡體   English   中英

如何處理與 HttpClient 的並發沖突?

[英]How to handle Concurrency Conflicts with HttpClient?

在看到數據庫中的更改后,我無法弄清楚如何編輯該行。

  • 我有一個 API 項目和一個 MVC 項目。 我在我的 API 中使用 CRUD,並用我的 MVC 和 HttpClient 調用它們
  • 我有一個public byte[] RowVersion { get; set; } public byte[] RowVersion { get; set; } public byte[] RowVersion { get; set; }具有屬性[Timestamp]的屬性。
  • 我有一個 clientFactory,我在其中執行 CreateClient() 以執行PutAsync("api.example.com/{id}")操作。
  • 我的 putasync 操作上的HttpResponseMessage variable返回StatusCode(409) ,因為我的 API 成功檢測到並發沖突。
  • 我設法在更新並發之前顯示錯誤消息; 新客戶端clientFactory.CreateClient()的幫助下顯示數據庫(newsDb)中新更新的行,並將它們與輸入(新聞)進行比較。
  • 然后我設置news.RowVersion = newsDb.RowVersion並重新顯示 View(news)。

再次點擊保存后,什么也沒有發生——沒有重定向,沒有更改——並發錯誤仍然存在:

[HttpPost("edit/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditNewsArticle(int id, [Bind("NewsId,Author,Title,Content,CreatedDate,HashTags,RowVersion")] News news)
{
    if (id != news.NewsId)
    {
        return NotFound();
    }

    if (ModelState.IsValid)
    {
        news.UpdatedDate = DateTime.Now;
        string json = JsonConvert.SerializeObject(news);
        HttpResponseMessage putTask = await clientFactory.CreateClient().PutAsync($"https://localhost:44331/api/News/{id}", new StringContent(json, Encoding.UTF8, "application/json"));

        if (putTask.IsSuccessStatusCode)
        {
            return RedirectToAction(nameof(Index));
        }
        else if (putTask.StatusCode == HttpStatusCode.Conflict)
        {
            string jsonDb = await clientFactory.CreateClient().GetStringAsync($"https://localhost:44331/api/News/{id}");
            News newsDb = JsonConvert.DeserializeObject<News>(jsonDb);

            if (newsDb is null)
            {
                ModelState.AddModelError(string.Empty, $"Unfortunately, the news item you edited has already been deleted by another user.");
            }

            if (newsDb.Title != news.Title)
            {
                ModelState.AddModelError("Title", $"Title in database: {newsDb.Title}");
            }
            if (newsDb.Author != news.Author)
            {
                ModelState.AddModelError("Author", $"Author in database: {newsDb.Author}");
            }
            if (newsDb.Content != news.Content)
            {
                ModelState.AddModelError("Content", $"Content in database: {newsDb.Content}");
            }
            if (newsDb.HashTags != news.HashTags)
            {
                ModelState.AddModelError("HashTags", $"HashTags in database: {newsDb.HashTags}");
            }

            ModelState.AddModelError(string.Empty,
            "Editing was canceled as the selected news item was changed by someone else in the meantime." +
            "The values ​​of the change are now shown below, which are derived from the database" + 
            "If you still want to edit the user, click Save again.");

            news.RowVersion = newsDb.RowVersion;
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Unknown error. Contact a support.");
            return View(news);
        }
    }

    return View(news);
}

並發成功顯示,但保存不會應用這些新更改,在確認它們已更改后

API 放:

[HttpPut("{id}")]
public async Task<IActionResult> PutNews(int id, [FromBody] News news)
{
    if (id != news.NewsId)
    {
        return BadRequest();
    }

    context.Entry(news).State = EntityState.Modified;

    try
    {
        await context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!NewsExists(id))
        {
            return NotFound();
        }
        else
        {
            return StatusCode(409);
        }
    }

    return CreatedAtAction("GetNews", new { id = news.NewsId }, news);
}

我發現了我的問題。 我需要調用 ModelState.Clear(); 在反序列化“jsonDb”之后,還從屬性中的 Bind 中刪除 RowVersion。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM