C# HttpWebRequest/HttpResponse:如何在响应中发送数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2246991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:45:24  来源:igfitidea点击:

HttpWebRequest/HttpResponse: How to send data in the response?

c#.nethttpwebrequesthttpresponse

提问by user252816

I have a client and a server.

我有一个客户端和一个服务器。

On the client side I have:

在客户端,我有:

HttpWebRequest request = 
    (HttpWebRequest)WebRequest.Create("http://localhost/fa/Default.aspx");
request.Method = "POST";                

byte[] data = Encoding.ASCII.GetBytes(GetSAMLRequestB64());

request.ContentType = "text/xml";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();

On the server side I have:

在服务器端,我有:

public void ProcessRequest(HttpContext httpContext) 
{
    HttpResponse response = httpContext.Response;             
    response.Clear();
    response.BufferOutput = true;
    response.StatusCode = 200; // HttpStatusCode.OK;
    response.Write("Hello");
    response.ContentType = "text/xml";
    response.End();
}

The client receives the response with the correct StatusCode. Although, if I do (int)response.ContentLength;on the client I get 0. I can't read the string "Hello" after I receive the response (client side).

客户端收到带有正确StatusCode. 虽然,如果我(int)response.ContentLength;在客户端上这样做,我会得到 0。在收到响应(客户端)后,我无法读取字符串“Hello”。

采纳答案by m0sa

Perhaps setting the content type before the actual write or flushing the stream would help.

也许在实际写入或刷新流之前设置内容类型会有所帮助。

回答by John Saunders

You didn't set ContentLength on the server. Maybe that would help?

您没有在服务器上设置 ContentLength。也许这会有所帮助?