我是webapi的新手,并开发了一个小的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;
}
}
[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之后我怎么能{j}到客户类deserialize
。
这就是我调用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);
}
}
}
T 他的错误信息是:
“Newtonsoft.Json.JsonSerializationException”类型的例外 发生在Newtonsoft.Json.dll但未在用户代码中处理
其他信息:无法反序列化当前的JSON对象 (例如{“name”:“value”})进入'WebAPIClient.Response []'类型因为 该类型需要一个JSON数组(例如[1,2,3])来反序列化 正确。
为什么响应会导致此错误?
答案 0 :(得分:16)
在客户端上,包括对内容的阅读:
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>>(customerJsonString);
// Do something with it
}
更改您的WebApi,不要使用您的Response类,而是使用IEnumerable
Customer
。使用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而不是您自己的this post。 200 Ok,401 Unauthorized等。另外config()
关于如何返回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;
}
}
答案 1 :(得分:0)
或者您可以在同一电话上进行转化
TResponse responseobject = response.Content.ReadAsAsync<TResponse>().Result;
responseJson += "hostResponse: " + JsonParser.ConvertToJson(responseobject);
//_logger.Debug($"responseJson : {responseJson}", correlationId);