gpt4 book ai didi

c# - 从 HTTPRuntime 缓存中检索图像

转载 作者:行者123 更新时间:2023-11-30 16:24:23 26 4
gpt4 key购买 nike

我正在尝试从 HTTPRuntime 缓存中保存和检索图像,但出现异常。我能够将流保存到缓存中,但是当我尝试检索它时,出现异常:

the request was aborted. The connection was closed unexpectedly

这是我的代码:

public void ProcessRequest(HttpContext context)
{
string courseKey = context.Request.QueryString["ck"];
string objKey = context.Request.QueryString["file"];

if(HttpRuntime.Cache[objKey] !=null)
{
using (Stream stream = (Stream)HttpRuntime.Cache[objKey]) // here is where I get an exception
{
var buffer = new byte[8000];
var bytesRead = -1;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
context.Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
return;
}
var response = Gets3Response(objKey, courseKey, context);

if (response != null)
{
using (response)
{
var MIMEtype = response.ContentType;
context.Response.ContentType = MIMEtype;
var cacheControl = context.Response.CacheControl;
HttpRuntime.Cache.Insert(objKey, response.ResponseStream, null, DateTime.UtcNow.AddMinutes(20), Cache.NoSlidingExpiration);
using (Stream responseStream = response.ResponseStream)
{
var buffer = new byte[8000];
var bytesRead = -1;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
context.Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
}
}
}

这是我遇到的异常

Exception

最佳答案

这段代码相当困惑。首先,您正在缓存 response.ResponseStream,但它已包装在 using block 中。因此,当您到达 HttpRuntime.Cache.Insert 时,response.ResponseStream 已经处理并关闭。因此错误。

您不应该缓存流。一方面,一旦您部署了分布式缓存服务,您的方法将无法实现。你需要重构这个。考虑:

public class CacheAsset
{
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
}

CacheAsset GetAsset(HttpContext context)
{
string courseKey = context.Request.QueryString["ck"];
string objKey = context.Request.QueryString["file"];

var asset = context.Cache[objKey] as CacheAsset;

if (asset != null) return asset;

using (var response = Gets3Response(objKey, courseKey, context))
using (var stream = new MemoryStream())
{
var buffer = new byte[8000];
var read = 0;

while ((read = response.ReponseStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, read);
}

asset = new CacheAsset
{
FileName = objKey,
ContentType = reponse.ContentType,
Content = stream.ToArray()
};
context.Cache.Insert(objKey, asset, null, DateTime.UtcNow.AddMinutes(20), Cache.NoSlidingExpiration);
}

return asset;
}

public void ProcessRequest(HttpContext context)
{
var asset = GetAsset(context);

context.Response.ContentType = asset.ContentType;
context.Response.BinaryWrite(asset.Content);
}

关于c# - 从 HTTPRuntime 缓存中检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10926217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com