在 ASP.NET Core Web Api 中发布流 [英] Post Stream in ASP.NET Core Web Api
问题描述
你好,Stack Overflow 可爱的人们.从昨天开始,我遇到了问题,从那时起我就一直在浏览 SO.我有一个 UWP 客户端和 ASP.NET Core Web Api.我只是想向我的 web api 发送一个流,但这确实比我想象的要困难得多.
Hello lovely people of Stack Overflow. Since yesterday I have a problem and I have been browsing SO since then. I have a UWP Client and ASP.NET Core Web Api. I just want to send a stream to my web api but indeed this occurred to be harder task than i thought.
我有一个只有一个属性的类.Stream
属性,如下所示:
I have a class which I have only one property. The Stream
property as you can see below:
public class UploadData
{
public Stream InputData { get; set; }
}
然后这是我的 Web Api 代码:
Then Here is my code from my Web Api:
// POST api/values
[HttpPost]
public string Post(UploadData data)
{
return "test";
}
我试图从 body 中读取流,但结果是一样的.我可以点击 post 方法 UploadData
is not null 但我的 InputData
总是 null
.
I have tried to read the stream From body but the result is same.
I can hit the post method UploadData
is not null but my InputData
is always null
.
这是我的 UWP 发布请求代码.
Here is my UWP's code for post request.
private async void PostStreamButton_OnClick(object sender, RoutedEventArgs e)
{
using (var client = new HttpClient())
{
var dummyBuffer = new UnicodeEncoding().GetBytes("this is dummy stream");
var dummyStream = new MemoryStream(dummyBuffer).AsRandomAccessStream().AsStream();
var requestContent = new MultipartFormDataContent();
var inputData = new StreamContent(dummyStream);
inputData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
requestContent.Add(inputData, "inputData");
HttpResponseMessage response = client.PostAsync("url", inputData).Result;
}
}
我尝试了各种内容类型,但它们似乎都不起作用,我不知道为什么.我真的很感激所有的帮助.
I have tried various of content types which none of them seems to work and I have no idea why. I would really appreciate all the help.
推荐答案
在客户端发送流内容而不是整个模型.
On client side send the stream content not the whole model.
private async void PostStreamButton_OnClick(object sender, RoutedEventArgs e) {
using (var client = new HttpClient()) {
var dummyBuffer = new UnicodeEncoding().GetBytes("this is dummy stream");
var dummyStream = new MemoryStream(dummyBuffer).AsRandomAccessStream().AsStream();
var inputData = new StreamContent(dummyStream);
var response = await client.PostAsync("url", inputData);
}
}
注意:不要将 .Result
阻塞调用与异步调用混用.这些往往会导致死锁.
NOTE: Do not mix .Result
blocking calls with async calls. Those tend to cause deadlocks.
在服务器更新操作
// POST api/values
[HttpPost]
public IActionResult Post() {
var stream = Request.Body;
return Ok("test");
}
这篇关于在 ASP.NET Core Web Api 中发布流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!