我是 JSON 新手,需要帮助。我有一些 JSON 在 jquery 中工作,并从我在 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;
}
}
那是在网络服务上,我希望能够使用这段代码调用“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");
我收到一个 Not Acceptable 媒体错误。
在此先感谢您,希望这对其他人有帮助。
最佳答案
首先,您错过了要在 web 服务中添加的 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; }
关于c# - 使用 C# HttpWebRequest 将 json 发送到 web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510437/