【问题标题】:Issue is why my Web API not returning JSON问题是为什么我的 Web API 不返回 JSON
【发布时间】:2016-08-26 10:18:31
【问题描述】:

查看我的 Web api 控制器操作。我从我的操作返回一个响应类,其中包含客户数据、状态和消息等,但是当我从浏览器调用我的 Web 操作时,操作仅返回此符号 {},这很奇怪。查看我的网络 api 代码

我的代码如下

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

[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
    var Response=new Response(true, "SUCCESS", repository.GetAll());
    //return Response;
    //return Request.CreateResponse(HttpStatusCode.OK, Response);
    HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
    return response;
}

[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));
}

public HttpResponseMessage PostCustomer(Customer customer)
{
    customer = repository.Add(customer);
    var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);

    string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
    response.Headers.Location = new Uri(uri);
    return response;
}

public void PutProduct(string customerID, Customer customer)
{
    customer.CustomerID = customerID;
    if (!repository.Update(customer))
    {
    throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

public void DeleteProduct(string customerID)
{
    Customer customer = repository.Get(customerID);
    if (customer == null)
    {
    throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    repository.Remove(customerID);
}
}

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

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

public class Customer
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }

    public string Address { get; set; }

    public string Region { get; set; }

    public string PostalCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
}

我是这样从winform using httpclient打电话的

    var baseAddress = "http://localhost:38762/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);
            }
        }
    } 

告诉我 GetAll actions 的代码有什么问题,它没有返回 json 而是返回 {}

我必须返回我的响应类而不是IEnumerable&lt;Customer&gt;,所以请告诉我要在代码中更改什么的路径。

如果我的方法看起来像

    [HttpGet, Route("GetAll")]
    public Response GetAllCustomers()
    {
        var Response = new Response(true, "SUCCESS", repository.GetAll());
        //return Response;
        //return Request.CreateResponse(HttpStatusCode.OK, Response);
        //HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
        return Response;
    }

OR 

    [HttpGet, Route("GetAll")]
    public HttpResponseMessage GetAllCustomers()
    {
        var Response=new Response(true, "SUCCESS", repository.GetAll());
        //return Response;
        //return Request.CreateResponse(HttpStatusCode.OK, Response);
        HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
        return response;
    }

但不返回任何数据或 json。只返回 {} 表示 null。

这样我就可以向我的 web api 发出指令,结果它应该返回 json。

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}

【问题讨论】:

    标签: asp.net-web-api httpclient


    【解决方案1】:

    我认为问题可能是您已经在 Response 中发送了 SUCCESS,然后使用 Request.CreateResponse(..) 方法创建了另一个响应。

    您可以尝试如下修改您的方法

     public Response GetAllCustomers()
            {
                var data = repository.GetAll();
                if (data !=null)
                   return Request.CreateResponse(HttpStatusCode.OK, data);
                else
                   return Request.CreateErrorResponse(HttpStatusCode.NotFound,"No records found");
            }
    

    您可以退回这些 HttpStatusCodes

    【讨论】:

    • 如何使用CreateResponse 向客户端返回错误消息?假设我正在将数据从客户端发送到 web api,而 web api 是验证,如果数据不正确,假设客户名称为空或 null 或电子邮件错误,那么我们必须向客户端返回错误消息........ ..告诉我我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    相关资源
    最近更新 更多