使用C#HttpWebRequest将json发送到Web服务

时间:2013-12-11 04:20:47

标签: c# json httpwebrequest

我是JSON的新手,需要帮助。我在jquery中运行了一些JSON,并从我在Web上运行的Web服务中正确地获取信息。但是,我无法在C#中使用HttpWebRequest来使用它。我将在下面发布代码。

/// <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;
    }
}

这是在Web服务上,我希望能够使用此代码调用“callJson(string x)”,

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;
        }

我一直收到内部服务器错误。当我将类型更改为application / json并添加时,

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

我收到了一个未被接受的媒体错误。

提前感谢您,希望这有助于其他人。

1 个答案:

答案 0 :(得分:35)

首先,您错过了要在webservice中添加的ScriptService属性。

  

[ScriptService]

然后尝试以下方法通过JSON调用webservice。

        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;
        }