Rick Roy
Rick Roy

Reputation: 1738

Remove xml header from C# webservice

I need to build an API using C# webservice, which needs to return values in json format.

Currently I have the following lines of code

namespace WebService1
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return new JavaScriptSerializer().Serialize(new { errMsg = "test" });
        }
    }
}

The output of this when the post method is invoked is

<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://tempuri.org/">{"errMsg":"test"}</string>

But this isn't a valid json how do I make the webservice return the json object only and not the xml headers?

Upvotes: 1

Views: 1315

Answers (1)

Sebo Zoltan
Sebo Zoltan

Reputation: 203

Calling this webservice with header Content-Type: application/json will automatically transform the response to json and your xml will be gone.

Upvotes: 2

Related Questions