如何将文件放入HttpResponseMessage内容?

时间:2015-04-17 20:23:34

标签: c# asp.net file asp.net-web-api httpresponse

我想在HttpResponseMessage内容中返回一个这样的文件:

return Request.CreateResponse(HttpStatusCode.OK, {{a file here}});

或者这个:

return new HttpResponseMessage() {
   StatusCode = HttpStatusCode.OK; 
   Content = {{ a file "example.zip" here}}
};

这可能吗?

1 个答案:

答案 0 :(得分:3)

您可以使用System.Net.Http.HttpContent.StreamContent实例将FileStream对象添加到HttpResponseMessage的Content属性中。像这样:

        // Return archive stream
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(fileStream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
            FileName = fileName.ToString()
        };

请注意,您可能还应该在实际应用程序中为文件内容添加MD5校验和。