【问题标题】:Returning an error message REST API with Xamarin使用 Xamarin 返回错误消息 REST API
【发布时间】:2018-07-09 20:00:44
【问题描述】:

我正在开发(至少尝试...)一个连接到 API 的 xamarin android 应用程序。以下是我尝试使用 Post 执行的操作的基本示例。我不确定如何将错误消息(不仅仅是代码)返回给客户端?只要能提供完整的示例,我愿意接受更好的方法。

API 代码:

[HttpPost("Consume")]//*
public IActionResult ConsumeInventory([FromBody] Part part)
{
    try
    {
        _repo.ConsumeInventory(part);
    }
    catch (Exception ex)
    {
        //ModelState.AddModelError("Error", ex.Message);
        return NotFound("Not Enough Inventory");
    }

    return Ok(part);
}

客户端调用:

public async Task<HttpResponseMessage> UpdatePartAsync(Part part, string post_url)
{
    string jsonString = JsonConvert.SerializeObject(part);
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsync("invcount/" + post_url, new StringContent(jsonString, Encoding.UTF8, "application/json"));

    if (response.StatusCode == HttpStatusCode.NotFound)
    {...//Would like to display "Not enough Inventory" in here}

    return response;        
}

【问题讨论】:

    标签: c# android rest xamarin


    【解决方案1】:

    即使API调用不成功,你也可以使用HttpResponseMessage.Content.ReadAsStringAsync()read the content响应的HttpResponseMessage.Content.ReadAsStringAsync()

    if (response.StatusCode == HttpStatusCode.NotFound)
    {
        // Would like to display "Not enough Inventory" in here}
        var resposeContent = response.Content?.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<ServerResponse>(resposeContent);
    
        // this guy will have your human-readable description or in your case, you can display the whole `result` string
        Debug.WriteLine(result.Description); 
    }
    

    并在您设计 API 时定义您的 ServerResponse 类。我经常从同一个基类继承我的所有 API 响应,因此在客户端我可以先解析它们以检查来自服务器的自定义指令(自定义代码并不总是错误)消息:

    public class ServerResponse
    {
         public string Code {get;set;}
         public string Description {get;set;}
    }
    

    ps:请注意,HttpResponseMessage.Content 在某些情况下可能为空。

    【讨论】:

      【解决方案2】:

      您的问题与 Xamarin 无关。在这种情况下,Xamarin 应用只是一个使用您的 API 的前端。

      一般来说,您应该概括您的错误响应,并在需要时将异常记录到 DB 以进行进一步分析。 JSON 示例:

      {
        "Code": 1000,
        "Description": "Human readable description",
        "Id": "6a154fd3-4142-4a9c-80b5-c635e84123fa"
      }
      

      Code 用于系统内部错误代码,Id 用于识别数据库中的堆栈跟踪。因此,您的最终用户将获得一个很好的人类可读描述和一个Id,他可以用来联系支持。

      从技术上讲,使用ExceptionFilterAttribute 来捕获并向您的客户返回一般错误响应。阅读Global Error Handling in ASP.NET Web API 2 也可以让您更好地了解。

      在您从 API 获得响应后,您可以在客户端应用中检查响应是否包含成功状态代码:

      if (!response.IsSuccessStatusCode)
      {
          // Deserialize error message
      }
      

      P.S.:Stackoverflow 不是编码服务,所以不会有完整的例子。希望您能从我的回答中得到一些关于如何以更好的方式处理它的想法。

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2012-09-19
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-07
        • 1970-01-01
        • 2012-10-21
        相关资源
        最近更新 更多