我开发了一个小的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;
}
}
我的Web API及其操作
[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后,我应该如何将其反序列化为客户类。
这是我调用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();
}
问题
如何在客户端获取WebAPI返回的响应类
如何从响应类中提取json
如何在客户端将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);
}
}
}
错误内容为:
发生了类型为 'Newtonsoft.Json.JsonSerializationException' 的异常,但未在用户代码中处理。
其他信息: 无法将当前的 JSON 对象(例如 {"name":"value"})反序列化为类型 'WebAPIClient.Response[]',因为该类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。
为什么响应会引起此错误?
var customerJsonString = await response.Content.ReadAsStringAsync();
时,只会在customerJsonString变量中得到这个符号{}
。我犯了什么错误? - Monojit Sarkarresponse.Content.ReadAsStringAsync();
获取响应字符串(即JSON),然后你可以使用类似JsonConvert的工具将该Json字符串反序列化为C#对象。你需要在客户端中使用相同的类来进行反序列化 - 可以创建一个共享库或其他东西,以便在两个项目中导入它(仅供参考)。 - Geoff James