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

 夜灬哭味 发布于 2023-02-11 16:19

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

/// 
/// Summary description for VBRService
/// 
[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");

我收到了一个不被接受的媒体错误.

提前谢谢你,希望这有助于其他人.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有