Csharp/C#教程:使用C#HttpWebRequest将json发送到Web服务分享


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

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

///  /// Summary description for VBRService ///  [WebService(Namespace = "https://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", "https://test.visitblueridge.com/callJson"); 

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

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

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

[ScriptService]

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

上述就是C#学习教程:使用C#HttpWebRequest将json发送到Web服务分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  var webAddr = "https://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; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/962332.html

(0)
上一篇 2021年11月27日
下一篇 2021年11月27日

精彩推荐