问题是我的Web API没有返回JSON的原因

时间:2016-08-26 10:18:31

标签: asp.net-web-api httpclient

查看我的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<Customer>,因此请向我展示代码中要更改的内容。

如果我的方法看起来像

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

1 个答案:

答案 0 :(得分:0)

我认为问题可能是您已经在响应中发送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