Question

I am new to JSON and need help. I have some JSON working in jquery and get the information back correctly from the web service I have running on the web. However, I can't get it to work using HttpWebRequest in C#. I will post the code below.

/// <summary>
/// Summary description for VBRService
/// </summary>
[WebService(Namespace = "http://test.visitblueridge.com/")]
[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 VBRService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string callJson(string x)
    {
        return "Worked =" + x;
    }
}

That is on the web service and I want to be able to call "callJson(string x)" using this code,

var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

I keep getting an internal server error. When I change the type to application/json and add,

request.Headers.Add("SOAPAction", "http://test.visitblueridge.com/callJson");

I get an unaccepted media error.

Thank you in advance and hope this helps others.

Was it helpful?

Solution

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top