gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:58:44 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com