1

I would like to create webservices returning json. However, I'm always getting 'text/html' as the responses content type.

First shot:

 public StringContent Get()
 {
     List<Cell> list = new List<Cell>();
     Cell c = new Cell("Cell1");
     Cell c2 = new Cell("Cell2");
     list.Add(c);
     list.Add(c2);

     return new StringContent(
       Newtonsoft.Json.JsonConvert.SerializeObject(list),
       Encoding.UTF8,
       "application/json");
 }

Responsecontent: System.Net.Http.StringContent

second shot:

    public List<Cell> Get()
    {
        Cell c = new Models.Cell("Cell1");
        List<Cell> list = new List<Cell>();
        list.Add(c);
        return list;
    }

Responsecontent: System.Collections.Generic.List`1[TestApp.Models.Cell]

This is how I access the endpoint:

$.ajax({
            url: "http://localhost:54787/Cell/Get",
            type: "GET",
            contentType:"application/json",
            accepts: {
                text: "application/json"
            },       
            success: function (response) {
                $("#result").html(JSON.parse(response));
            },
            error: function (xhr, status) {
                alert("error");
            }
        });

enter image description here

user66875
  • 2,772
  • 3
  • 29
  • 55
  • How are you testing the endpoint? – zulqarnain Sep 05 '16 at 09:46
  • I'm calling `/Cell/Get` from chrome. I have also tried a jQuery $.ajax get Request and checked the network monitor of chrome. – user66875 Sep 05 '16 at 09:48
  • 1
    Have you seen this? http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome?rq=1 – zulqarnain Sep 05 '16 at 09:52
  • @user66875, The framework's content negotiator returns the media type asked for by the request provided it can support it. If you are calling it from a browser then the browser by default will ask for `text/html` – Nkosi Sep 05 '16 at 10:29

1 Answers1

1

If you have no good reason to do serialization manually, you should use Web API default mechanism by returning object instead of StringContent. For example, you can change your method to return List<Cell> directly.

public List<Cell> Get()
{
     // return List<Cell> just like you write a typical method
}

This way, you will not get text/html anymore. However, you will still get XML in Chrome. It is because Chrome's default HTTP Accept header contains application/xml, and it is supported by default in Web API. If you have no need to support XML result, so you can remove it by the following code during startup (maybe in Global.asax)

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

PS: If you don't know whether you need XML or not, then you don't need it.

tia
  • 9,518
  • 1
  • 30
  • 44
  • Thank you. I have updated my post and added the result of your code. I really don't understand why it still returns `text/html`. – user66875 Sep 05 '16 at 11:22