1

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?

1
  • have you considered using asp.net web api? Commented Jul 21, 2015 at 11:38

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.