Cos*_*lis 16 c# asp.net stream asp.net-web-api2
我有一大堆存储在安全服务器上的图像,其中一些需要在面向世界的门户上显示.门户网站的服务器位于DMZ内部,允许请求但阻止直接请求进入安全域.图像使用SOLR编目,可以通过内部(apache?)服务器下载http://intenalname/folderA/folderAB/file.jpg
在我的内部我PhotoController可以创建一个实例WebClient,给它url并得到一个MemoryStream.如果我尝试使用这个内存流来填充response.content,我会得到一个空响应(每个fiddler).如果我使用内存流写入本地文件,然后读取文件(使用FileStream和FileInfo)它"按预期"工作.
我应该能够从一个MemoryStream到StreamContent没有经过文件系统(不应该)?但怎么样?默认构造函数StreamContent(stream)接受内存流实例而没有编译器错误......但它只是'不起作用'.
HttpResponseMessage response = Request.CreateResponse();
using (WebClient webClient = new WebClient())
{
string url = string.Format(PHOTO_GET, filePath);
using (MemoryStream memoryStream = new MemoryStream(webClient.DownloadData(url)))
{
// If these lines are unremarked the stream moves 'through' the file system and works (?!)
//memoryStream.Position = 0;
//string tempName = @"c:\test\" + Guid.NewGuid().ToString() + ".jpg";
//var fs = new FileStream(tempName, FileMode.OpenOrCreate);
//stream.CopyTo(fs);
//fs.Close();
//FileInfo fi = new FileInfo(tempName);
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
//response.Content = new StreamContent(fi.ReadStream());
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("render");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");//("application/octet-stream");
response.Content.Headers.ContentLength = memoryStream.Length;
}
}
return response;
Run Code Online (Sandbox Code Playgroud)
通过Fiddler进行测试时,我得到:
[Fiddler] ReadResponse()失败:服务器没有为此请求返回完整的响应.服务器返回0个字节.
(通过FileStream时,Fiddler会向我显示图像.)
Nko*_*osi 27
在您的代码中,内存流在将内容传递给响应之前就会被释放.返回的响应将使用已处理的内存流,因此无需返回,因此fiddler中的0字节.
HttpResponseMessage response = Request.CreateResponse();
using (WebClient webClient = new WebClient())
{
string url = string.Format(PHOTO_GET, filePath);
var memoryStream = new MemoryStream(webClient.DownloadData(url));
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("render");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = memoryStream.Length;
}
return response;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21927 次 |
| 最近记录: |