在ASP.NET Core Web Api中发布流 [英] Post Stream in ASP.NET Core Web Api

查看:98
本文介绍了在ASP.NET Core Web Api中发布流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,Stack Overflow的好朋友。
从昨天开始我遇到了问题,从那以后我一直在浏览。
我有一个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";
}

我尝试从主体读取流,但结果相同。
我可以点击发布方法 UploadData 不为空,但是我的 InputData 始终为

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆