c# - 使用 C# HttpWebRequest 将 json 发送到 web 服务

标签 c# json httpwebrequest

我是 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/

相关文章:

c# - ProgressBar 的默认前景色

javascript - Sequelize - 如何仅返回数据库结果的 JSON 对象?

python - 如何使用python多字典中的键获取值

c# - WebClient restful 删除

ruby - 怎么看别人的论坛

c# - 为什么在 using 语句中声明的变量被视为只读?

c# - 如果字符串格式匹配,则提取数字

c# - 检查URL是否存在-HTTP请求始终返回异常

c# - TreeNode 单击与 TreeView 单击

json - Node - NPM 不断抛出未知错误