如何使用消息发送状态码 .NET Core Web API

How to send status code with message .NET Core Web API

我正在处理两个 Web API 项目。我收到一个 API 对另一个 API 的响应,其中包含状态代码和消息。使用以下方法我需要发送带有消息的状态代码。

[HttpPost]
public async Task<string> CreateOrder(Order order)
{
        string jsonResponse = null;
        HttpClient client = new();

        var payload = new JsonPayloadBody();
        payload.Api = new Api();
        payload.Header = new OrderHeader();

        payload.Api.NAME = "CREATE";
        payload.Api.QUERY = "CREATE_ORDER";

        payload.Header.INTERFACE_RECORD_ID = order.INTERFACE_RECORD_ID;            
        payload.Header.INTERFACE_ACTION_CODE = order.INTERFACE_ACTION_CODE;                                                                               

        payload.LineItems.Add(li); }

        var orderPayload = JsonConvert.SerializeObject(payload);
        var payloadObj = JsonConvert.DeserializeObject<MHScaleMessage>(orderPayload);
        var requestPayload = payloadObj.ToJsonString();
        var stringContent = new StringContent(requestPayload, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync(_baseUrl, stringContent);

        if (response.IsSuccessStatusCode)
        {
             jsonResponse = await response.Content.ReadAsStringAsync();
            _logger.LogInformation(jsonResponse);
            _logger.LogInformation("Order created successfully");
        }
        else
        {         
            _logger.LogInformation("Order creation filed");
        }

        return jsonResponse;
}

使用这条线

jsonResponse = await response.Content.ReadAsStringAsync();

我能够向邮递员发送消息,但它始终发送 200 状态代码。所以我需要根据响应发送状态码,例如:

return NotFound 
return Ok 
return BadRequest

这里是 A Web ApiB Wen Api。您使用 AB 获取带有状态代码的响应。 A的任务是获取B的状态码。你也得到200状态码的原因是什么B的状态码,A总能成功得到状态码,所以A总是return200.

如果您想添加来自 A 的不同响应消息,您可以添加一些代码,例如:

if (response.IsSuccessStatusCode)
{
     jsonResponse = await response.Content.ReadAsStringAsync();
     _logger.LogInformation(jsonResponse);
     _logger.LogInformation("Order created successfully");
}
else if(response.StatusCode == (System.Net.HttpStatusCode)404)
{
     //..add NotFound message......
}
else if(response.StatusCode == (System.Net.HttpStatusCode)400)
{
     //..add BadRequest message......
}
      //......

如果想要return状态码,可以添加下面的代码

[HttpPost]
//if you want to get the status codo , you need to return a StatusCodeResult Class in your action 
//so i change Task<string> to Task<IActionResult>
public async Task<IActionResult> CreateOrder(Order order)
{
    //......

    else if(response.StatusCode == (System.Net.HttpStatusCode)400)
        {
             //if you want to use jsonResponse to do some logger,you can try this 
             jsonResponse  = "BadRequest"
             _logger.LogInformation(jsonResponse);
             return BadRequest(jsonResponse  );
        }
}

注意 : 当您使用上面的代码创建 Badrequest 时会出现问题,当您从 A Web Api 获取 400 状态代码时,您不知道问题出在 A 还是 B.