Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1801
  • Last Modified:

Web API in WebForms app returning XML instead of JSON

I added Web API to my existing Web Forms (NOT MVC) ASP.NET application using these instructions:

http://blogs.msdn.com/b/henrikn/archive/2012/02/23/using-asp-net-web-api-with-asp-net-web-forms.aspx

http://dotnet.dzone.com/articles/web-api-aspnet-web-forms

But, they return XML.  
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
   <string>value1</string>
   <string>value2</string>
</ArrayOfstring>

Open in new window


I tried using JSON.NET...
    public string Get(int id)
    {
        DataTable person = MemberFunctions.GetContactInfo(id);
        return JsonConvert.SerializeObject(person);   
    }

Open in new window


and it generates the JSON I need but it is still wrapped in XML tags:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
    [{"Prefix":"Dr","FirstName":"Josh",   ....etc.......   }]
</string>

Open in new window

How can I get WebAPI in a WebForms app to return valid JSON instead of XML, preferably using JSON.NET?
0
joshbula
Asked:
joshbula
1 Solution
 
joshbulaAuthor Commented:
I ended up just removing the XmlFormatter by putting this in the Global.asax Application_Start (this is an existing WebForms application, originally written in VB, so the Global.asax is VB even though all my new classes and code are C#.)
        Dim formatters = GlobalConfiguration.Configuration.Formatters
        formatters.Remove(formatters.XmlFormatter)

Open in new window

But it was still adding quotes and escaping all the quotes, so I realized that it had to return a JObject, not a string, and then Parse it using JObject.Parse:
  public JObject Get(int id)
    {
        DataRow person = MemberFunctions.GetContactInfo(id).Rows[0];
        JObject output = JObject.Parse(JsonConvert.SerializeObject(person));
        return output;
    }

Open in new window

This requires using Newtonsoft.Json.Linq;

To convert an entire datatable or dataset, I ended up just using JsonConvert.SerializeObject without parsing it into a JObject:
string output = JsonConvert.SerializeObject(dataSet, Formatting.None);

Open in new window

and then a Response.Write() and Response.End() to prevent it from adding extra quotes and escaping stuff.
Httpcontext.Current.Response.Write(output);
HttpContext.Current.Response.End();

Open in new window

I'm not sure if that's the best way to do that, but it seems to be working.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now