Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post Stream in ASP.NET Core 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.

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; }
}

Then Here is my code from my Web Api:

// POST api/values
[HttpPost]
public string Post(UploadData data)
{
    return "test";
}

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.

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.

like image 726
Hasan Hasanov Avatar asked Feb 16 '17 10:02

Hasan Hasanov


1 Answers

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);
    }
}

NOTE: Do not mix .Result blocking calls with async calls. Those tend to cause deadlocks.

On server update action

// POST api/values
[HttpPost]
public IActionResult Post() {
    var stream = Request.Body;
    return Ok("test");
}
like image 101
Nkosi Avatar answered Oct 06 '22 13:10

Nkosi