使用C#将XML数据发布到Web服务

时间:2012-03-22 14:11:21

标签: c# xml web-services

我正在尝试将XML数据集发布到我的Web服务,但是当我尝试发送XML时出现500错误,如果我替换postData =“xmlMsg = Test”,则Web服务接受它,但不是我尝试发送XML

在我的网络服务中我使用

    [WebMethod]
    public string HelloWorld(string xmlMsg)
    {.......

我的应用程序使用

    URL = "http://localhost:55310/Service1.asmx/HelloWorld";
    method = "POST";
    postData = "xmlMsg=<NewDataSet> <People><PersonId>3293</PersonId> </People></NewDataSet>"

    public static string WRequest(string URL, string method, string postData)
    {
        string responseData = "";

        try
        {
            HttpWebRequest hwrequest = (HttpWebRequest)WebRequest.Create(URL);
            hwrequest.Timeout = 60000;
            hwrequest.Method = method;
            hwrequest.KeepAlive = false;

            if (hwrequest.Method == "POST")
            {
                hwrequest.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding = new UTF8Encoding();
                byte[] postByteArray = encoding.GetBytes(postData);
                hwrequest.ContentLength = postByteArray.Length;
                Stream postStream = hwrequest.GetRequestStream();
                postStream.Write(postByteArray, 0, postByteArray.Length);
                postStream.Close();
            }

            // Attempt to receive the WebResponse to the WebRequest.
            using (HttpWebResponse hwresponse = (HttpWebResponse)hwrequest.GetResponse())
            {
                if (hwresponse != null)
                { // If we have valid WebResponse then read it.
                    using (StreamReader reader = new StreamReader(hwresponse.GetResponseStream()))
                    {
                        XPathDocument doc = new XPathDocument(reader);
                        XPathNavigator xml = doc.CreateNavigator();
                        responseData = xml.ToString().Trim();

                        reader.Close();
                    }
                }

                hwresponse.Close();

            }


        }
        catch (Exception e)
        {
            responseData = "An error occurred: " + e.Message;
        }



        return responseData;
    }

任何人都可以看到我出错的地方,显然它不喜欢xml,但我不确定为什么或如何绕过它

0 个答案:

没有答案