c# - 使用 Xamarin 返回错误消息 REST API

标签 c# android rest xamarin

我正在开发(至少无论如何尝试...)一个连接到 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;        
}

最佳答案

即使 API 调用不成功,您也可以 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 在某些情况下可能为 null。

关于c# - 使用 Xamarin 返回错误消息 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529811/

相关文章:

android - FriendPickerFragment 是否已弃用/替换?应该使用什么?

java - 限制对 RESTful 服务的调用次数

python - 如何使用Python编写 "Hello World"RESTful API然后使用它

mysql - 通过 REST api(或其他传统方法)在 openedx 中创建用户

c# - 来自 WSDL 的 .NET 网络服务客户端

android - 将数据传递给 AsyncTask : execute(args) vs constructor?

c# - 使用多个参数调用控件时参数计数不匹配

android - 是否可以制作没有 Activity 的 apk?

c# - EntityFramework 避免打开/关闭连接?

c# - 来自整数的模型绑定(bind) TimeSpan