如何在ASP.NET MVC Web应用程序中使用HttpContent处理并发(状态409)错误? [英] How to handle concurrency (status 409) errors using HttpContent in ASP.NET MVC Web application?

查看:69
本文介绍了如何在ASP.NET MVC Web应用程序中使用HttpContent处理并发(状态409)错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Core 3.1 Web API和使用它的MVC应用程序.在MVC应用程序中,我设置了UserRepo,其中包含 Update 方法:

I'm working on a Core 3.1 Web API and an MVC application that uses it. In the MVC app I have UserRepo set up containing an Update method:

public async Task<User> Update(User user)
{
    HttpClient client = _clientFactory.CreateClient("namedClient");

    HttpResponseMessage response = await client.PutAsync($"api/Users/{user.Id}", ContentEncoder.Encode(user));
    try
    {
        response.EnsureSuccessStatusCode();
    }
    catch (Exception ex)
    {
        if ((int)response.StatusCode == StatusCodes.Status409Conflict)
        {
            throw;
        }
    }

    return await response.Content.ReadFromJsonAsync<User>();
}

回购被注入到服务中,服务被注入到控制器中,我想在该控制器中处理错误.

The repo is injected into a service, and the service is injected into a controller which is where I'd like to handle the error.

Update 方法不完整,因为我试图弄清楚如果rowversion值已过时,如何从API返回409错误.调用 response.EnsureSuccessStatusCode(); 时,如果不是成功代码,则会引发异常.我以为我可以将其冒泡到前端并在控制器操作中对其进行处理,但是异常对象没有包含足以识别这是409错误的特定内容:

The Update method is incomplete because I am trying to figure out how handle a 409 error which I return from API if the rowversion value was outdated. When response.EnsureSuccessStatusCode(); is called, an exception is thrown if it wasn't a success code. I imagined I could just have it bubble-up to the front-end and handle it in the controller action, but the exception object doesn't contain anything specific enough to identify that it's a 409 error:

因此,如果这冒到了控制器动作,那么我最好的办法就是尝试从消息中解析出状态代码,这似乎是个坏主意.

So if this bubbles up to the controller action, best I could to is try to parse out the status code from the message, which seems like a bad idea.

我可以找到一些人的示例,这些人从其Web API返回409个代码,但是当逻辑被分为不同的类而不是全都执行一次时,在MVC应用程序中将如何处理它们.

I can find examples of people returning 409 codes from their Web APIs, but not how they would be handled in an MVC app when logic is separated into different classes instead of being all in one action.

我该如何处理?我是否创建自定义异常并将其抛出?也许使用 ex.Data.Add()将其他数据添加到异常中并在操作中读取它?那会是个坏主意吗?

How could I handle this? Do I create a custom exception and throw that? Maybe add additional data to the exception with ex.Data.Add() and read it in the action? Would that be a bad idea?

推荐答案

感谢@Peter Csala,@ Craig H和@Filipe的建议,这是我确定的解决方案.

Thanks to suggestions from @Peter Csala, @Craig H, and @Filipe, this is the solution I settled on.

调用API的方法:

public async Task<User> Update(User user)
{
    HttpClient client = _clientFactory.CreateClient("namedClient");
    HttpResponseMessage response = await client.PutAsync($"api/Users/{user.Id}", ContentEncoder.Encode(user));
    await HttpResponseValidator.ValidateStatusCode(response);

    return await response.Content.ReadFromJsonAsync<User>();
}

我可以重用的静态方法,在并发错误期间会产生异常:

A static method I can reuse that will produce an exception during a concurrency error:

public static class HttpResponseValidator
{
    public static async Task ValidateStatusCode(HttpResponseMessage response)
    {
        if ((int)response.StatusCode < 200 || (int)response.StatusCode > 299)
        {
            string errorResponse = await response.Content.ReadAsStringAsync();
            if (response.StatusCode == HttpStatusCode.Conflict)
            {
                DBConcurrencyException ex = new DBConcurrencyException(errorResponse);
                throw ex;
            }
        }
    }
}

该异常一直持续到调用该API的方法的操作为止.我将其捕获到操作中,并在记录错误后进行处理.

The exception bubbles up all the way back to the action that called the method calling the API. I catch it in the action and handle it after logging the error.

这篇关于如何在ASP.NET MVC Web应用程序中使用HttpContent处理并发(状态409)错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆