gpt4 book ai didi

c# - 如何在 C# 中使用 HttpClient 读取 webapi 响应

转载 作者:太空狗 更新时间:2023-10-29 20:52:41 26 4
gpt4 key购买 nike

我开发了一个小型 webapi,它有一些操作并返回我的自定义类 Response

Response

public class Response
{
bool IsSuccess=false;
string Message;
object ResponseData;

public Response(bool status, string message, object data)
{
IsSuccess = status;
Message = message;
ResponseData = data;
}
}

我的带有操作的 webapi

[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
static readonly ICustomerRepository repository = new CustomerRepository();

[HttpGet, Route("GetAll")]
public Response GetAllCustomers()
{
return new Response(true, "SUCCESS", repository.GetAll());
}

[HttpGet, Route("GetByID/{customerID}")]
public Response GetCustomer(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new Response(true, "SUCCESS", customer);
//return Request.CreateResponse(HttpStatusCode.OK, response);
}

[HttpGet, Route("GetByCountryName/{country}")]
public IEnumerable<Customer> GetCustomersByCountry(string country)
{
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
}

现在我卡住了,我不知道如何读取从 webapi 操作返回的响应数据并从我的响应类中提取 json。获取 json 后,我如何反序列化那个 json 到客户类。

这是我调用 webapi 函数的方式:

private void btnLoad_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8010/");
// Add an Accept header for JSON format.
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// List all Names.
HttpResponseMessage response = client.GetAsync("api/customer/GetAll").Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Console.WriteLine("Response Message Header \n\n" + response.Content.Headers + "\n");
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
Console.ReadLine();
}
问题
  1. 如何在客户端获取webapi返回的响应类

  2. 如何从响应类中提取 json

  3. 如何在客户端反序列化json到客户类


我使用此代码但仍然出现错误。

    var baseAddress = "http://localhost:8010/api/customer/GetAll";
using (var client = new HttpClient())
{
using (var response = client.GetAsync(baseAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
var cust = JsonConvert.DeserializeObject<Response>(customerJsonString);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}

错误是:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'WebAPIClient.Response[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

为什么响应会导致此错误?

最佳答案

在客户端,包括阅读内容:

    HttpResponseMessage response = client.GetAsync("api/customer/GetAll").Result;  // Blocking call!  
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Console.WriteLine("Response Message Header \n\n" + response.Content.Headers + "\n");
// Get the response
var customerJsonString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Your response data is: " + customerJsonString);

// Deserialise the data (include the Newtonsoft JSON Nuget package if you don't already have it)
var deserialized = JsonConvert.DeserializeObject<IEnumerable<Customer>>(custome‌​rJsonString);
// Do something with it
}

更改您的 WebApi 以不使用您的 Response 类,而是使用 CustomerIEnumerable。使用 HttpResponseMessage 响应类。

您的 WebAPI 应该只需要:

[HttpGet, Route("GetAll")]
public IEnumerable<Customer> GetAllCustomers()
{
var allCustomers = repository.GetAll();
// Set a breakpoint on the line below to confirm
// you are getting data back from your repository.
return allCustomers;
}

根据评论中的讨论为通用响应类添加了代码,但我仍然建议您不要这样做并避免调用您的类 Response。你应该返回 HTTP status codes而不是你自己的。一个 200 Ok,一个 401 Unauthorised,等等。还有 this post关于如何返回 HTTP 状态代码。

    public class Response<T>
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public IEnumerable<T> ResponseData { get; set; }

public Response(bool status, string message, IEnumerable<T> data)
{
IsSuccess = status;
Message = message;
ResponseData = data;
}
}

关于c# - 如何在 C# 中使用 HttpClient 读取 webapi 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39162408/

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