不论成功状态代码如何,都使用RESTful API

时间:2018-08-17 11:12:05

标签: c# rest asp.net-web-api

请考虑以下代码段:

//API definition
[HttpPost]
[Route("api/v1/Customer")]
public IActionResult Post(CustomerModel cusomerModel)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest("BadRequest Data Here");
        }
        //...
        return OK("true");
    }
    catch(Exeption ex)
    {
        return InternalServerError("InternalServerError Data Here");
    }
}

public class CustomerModel
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string UserName { get; set; }
    [Required]
    public string SecretKey { get; set; }
}

//API consumer
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://localhost:8888/");
var httpResponseMessage = httpClient.PostAsJsonAsync("api/v1/Customer", customer).Result;

假设我是“ API使用者”,那么无论状态码如何,都可以通过该方法读取响应,例如:

switch(httpResponseMessage.StatusCode)
{
    case HttpStatusCode.Ok:
        var resultOk = httpResponseMessage.Content.ReadAsAsync<string>().Result; // where Result = "true"
        break;

    case HttpStatusCode.BadRequest:
        var resultBadRequest = httpResponseMessage.Content.ReadAsAsync<string>().Result; // where Result = "BadRequest Data Here"
        break;

    case HttpStatusCode.InternalServerError:
        var resultInternalServerError = httpResponseMessage.Content.ReadAsAsync<string>().Result; // where Result = "InternalServerError Data Here"
        break;
}

请告知是否可能。

1 个答案:

答案 0 :(得分:0)

我没有使用ReadAsAsync方法读取http内容,而是对http内容进行了序列化以返回流,然后使用流读取器从http内容中流出了我的原始内容:

var readStream = new StreamReader(httpResponseMessage.Content.ReadAsStreamAsync().Result, Encoding.UTF8);
switch (httpResponseMessage.StatusCode)
{
    case HttpStatusCode.Ok:
      var resultOk = readStream.ReadToEnd();
       break;

    case HttpStatusCode.BadRequest:
          var resultBadRequest = readStream.ReadToEnd();
       break;

    case HttpStatusCode.InternalServerError:
          var resultInternalServerError = readStream.ReadToEnd();;
       break;
}

如果HttpResponseMessage返回的StatusCode为OK,似乎ReadAsAsync函数只能流式传输内容。