C#将数据发布到ASP .Net应用程序

时间:2014-09-02 07:43:19

标签: c# xml httpwebrequest

我想要的只是将来自C#桌面应用程序的xml数据发送到ASP.Net网页。 我的C#代码看起来像这样。

public string SendRequest()
{   string data = "<?xml version="1.0"?><author>Gambardella, Matthew</author>";
    string _result;
    Uri uri = new Uri("http://localhost:62511/Default");
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "POST";
    request.ContentType = "text/xml";
    var writer = new StreamWriter(request.GetRequestStream());
    writer.Write(data);
    writer.Close();

    var response = (HttpWebResponse)request.GetResponse();

    var streamResponse = response.GetResponseStream();
    var streamRead = new StreamReader(streamResponse);
    Console.Write(response.StatusCode);
    _result = streamRead.ReadToEnd().Trim();
    streamRead.Close();
    streamResponse.Close();
    response.Close();
    return _result;
}

我的ASP .Net Code看起来像这样

protected void Page_Load(object sender, EventArgs e)
{
    using (var reader = new StreamReader(Request.InputStream))
    {
        string xml = reader.ReadToEnd();

        labelsam.Text = xml;
    }
    ....
}

labelsam是网页上的标签。但是我在标签中没有任何意义。无论如何都要检查是否收到数据。还有什么错误的代码?

1 个答案:

答案 0 :(得分:1)

您必须为post方法指定内容长度。

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength=data.Length; //ugly, but at least so
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();