Asp.net Web Api Streaming

2019-07-16 13:08发布

I have been trying to stream a file to my web service. In my Controller(ApiController) I have a Post function as follows:

public void Post(Stream stream)
{
    if (stream != null && stream.Length > 0)
    {
        _websitesContext.Files.Add(new DbFile() { Filename = Guid.NewGuid().ToString(), FileBytes= ToBytes(stream) });
        _websitesContext.SaveChanges();
    }
}

I have been trying to stream a file with my web client by doing the following:

public void UploadFileStream(HttpPostedFileBase file)
{
    WebClient myWebClient = new WebClient();
    Stream postStream = myWebClient.OpenWrite(GetFileServiceUrl(), "POST");
    var buffer = ToBytes(file.InputStream);
    postStream.Write(buffer, 0,buffer.Length);
    postStream.Close();
}

Now when i debug my web service, it gets into the Post function, but stream is always null. Was wondering if anyone may have an idea why this is happening?

3条回答
霸刀☆藐视天下
2楼-- · 2019-07-16 13:56

Web API doesn't model bind to 'Stream' type hence you are seeing the behavior. You could instead capture the incoming request stream by doing: Request.Content.ReadAsStreamAsync()

Example:

public async Task<HttpResponseMessage> UploadFile(HttpRequestMessage request)
    {
        Stream requestStream = await request.Content.ReadAsStreamAsync();

Note: you need not even have HttpRequestMessage as a parameter as you could always access this request message via the "Request" property available via ApiController.

查看更多
姐就是有狂的资本
3楼-- · 2019-07-16 14:06

You can replace with this code

var uri = new Uri(GetFileServiceUrl());
Stream postStream = myWebClient.OpenWrite(uri.AbsoluteUri, "POST");
查看更多
放我归山
4楼-- · 2019-07-16 14:12

RestSharp makes this sort of stuff quite easy to do. Recommend trying it out.

查看更多
登录 后发表回答