我正在使用ImageResizing库来调整大小并在我的C#Mvc应用程序中传递图像。在MVC应用程序中缓存图像的正确方法
有一件事情没有发生,虽然我的图片没有被缓存。
我很努力去理解为每幅图像适当地添加缓存需要什么。
我只需要知道我是否在写轨道?这会缓存我的图片吗?
我想我需要做的,是集FinalContentType,并FinalContentType在我ImageResizer_OnPostAuthorizeRequestStart(我不知道从哪里得到这些值)
然后,我希望在Application_PreSendRequestHeaders我可以使用以下代码正确设置缓存标头。
我已经使用了here所述方法的修改版本。
这里是我的代码:
private static void ImageResizer_OnPostAuthorizeRequestStart(IHttpModule sender2, HttpContext context)
{
string path = Config.Current.Pipeline.PreRewritePath;
if (!path.StartsWith(PathUtils.ResolveAppRelative("~/s3"), StringComparison.OrdinalIgnoreCase)) return;
Config.Current.Pipeline.SkipFileTypeCheck = true;
Config.Current.Pipeline.ModifiedQueryString["cache"] = ServerCacheMode.Always.ToString();
}
protected void Application_PreSendRequestHeaders(Object source, EventArgs e)
{
var app = source as HttpApplication;
HttpContext context = (app != null) ? app.Context : null;
if (context != null && context.Items != null && context.Items["FinalContentType"] != null && context.Items["LastModifiedDate"] != null)
{
//Clear previous output
//context.Response.Clear();
context.Response.ContentType = context.Items["FinalContentType"].ToString();
//FinalContentType is set to image/jpeg or whatever the image mime-type is earlier in code.
//Add caching headers
int mins = 1; //Or Configuration.AppSettings['whatever']
if (mins > 0)
{
context.Response.Expires = 1;
}
var lastModified = (DateTime?)context.Items["LastModifiedDate"]; //Set earlier in code.
if (lastModified != DateTime.MinValue)
{
Response.Cache.SetLastModified(lastModified.Value);
}
Response.Cache.SetCacheability(context.Request.IsAuthenticated ? HttpCacheability.Private : HttpCacheability.Public);
}
}
'OutputCacheAttribute'没有做你想做的事吗?链接:http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.108).aspx –
这些图像在运行时由库重新调整,以便缓存属性不起作用,也是我特别想要缓存的图像。 – shenku
为什么它不工作? MSDN表示它将缓存内存中的操作方法的输出。从本质上讲,我明白,无论写到响应中的任何内容都被保存在内存中,那就是你的二进制图像数据。 –