gpt4 book ai didi

c# - HttpRequestMessage/StreamContent,服务器端为空 Stream

转载 作者:太空狗 更新时间:2023-10-29 21:39:05 32 4
gpt4 key购买 nike

我想将流发布到 HTTP 服务器(由 OWINHost 托管),请参见下面的代码片段。当我使用 StringContent 传输 String 时,它工作正常。但是,如果我想传输带有 StreamContent 的 MemoryStream,则服务器端接收到的流是空的(出于测试目的,我通过在客户端反序列化 MemoryStream 来验证 MemoryStream 是正确的)。我做错了什么?

客户端:

...
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.ServiceBaseAddress);

// this works fine!
//request.Content = new StringContent("This is a test!!");

request.Content = new StreamContent(stream);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

HttpResponseMessage response = await client.SendAsync(request);
...

服务器端:

public class Startup {
public void Configuration(IAppBuilder app) {
app.Run(async context =>
{
var stream = new MemoryStream();
await context.Request.Body.CopyToAsync(stream);
stream.Seek(0, SeekOrigin.Begin);

// this works fine when I send StringContent
//StreamReader reader = new StreamReader(stream);
//String str = reader.ReadToEnd();

// when I send StreamContent the stream object is empty
IFormatter formatter = new BinaryFormatter();
ServiceRequest requestTest = (ServiceRequest)formatter.Deserialize(stream);

context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello World!");
});
}
}

最佳答案

我忘了包括:

stream.Seek(0, SeekOrigin.Begin);

在客户端。

关于c# - HttpRequestMessage/StreamContent,服务器端为空 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27202884/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com