在MVC中使用WebImage时,如何重定向至默认图片?
How to Redirect to a Default Image in Catch Block Instead of Using WebImage.Write()
我明白你想在捕获异常时,通过重定向到默认图片来替代直接输出图片的方式。这里有几个关键细节和修改后的完整代码:
首先,原来注释里的Redirect没生效大概率是因为没有正确解析~/开头的相对路径,或者没有使用ASP.NET的响应重定向方法。下面分两种常用场景给出解决方案:
场景1:在ASP.NET WebForms页面/用户控件中
如果这个方法是在WebForms的页面或用户控件里,你可以用Page.ResolveUrl把根相对路径转换成客户端能识别的URL,然后调用Response.Redirect:
[ImageOutputCache(Duration = 3000, Location = System.Web.UI.OutputCacheLocation.Client)] public void GetPic(string fn, int? w, int? h) { try { if (w > 1920) { w = 1920; } if (h > 1080) { h = 1080; } WebImage wi = new WebImage(@"~/img/" + fn); if (!h.HasValue) { Single ratio = (Single)wi.Width / (Single)wi.Height; h = (int)Math.Ceiling(w.Value / ratio); // 修正原代码逻辑:按传入的宽度计算对应高度 } wi .Resize(w.Value + 1, h.Value + 1, true, true) .Crop(1, 1) .Write(); } catch { // 解析默认图片的客户端可访问URL string defaultImageUrl = Page.ResolveUrl(@"~/img/default.jpg"); // 重定向并终止当前请求,避免后续代码引发异常 Response.Redirect(defaultImageUrl, endResponse: true); } }
场景2:在一般处理程序(ASHX)中
如果这个方法是在ASHX文件里,没有Page对象,就通过HttpContext来处理路径:
[ImageOutputCache(Duration = 3000, Location = System.Web.UI.OutputCacheLocation.Client)] public void GetPic(string fn, int? w, int? h) { try { // 原有逻辑不变 if (w > 1920) { w = 1920; } if (h > 1080) { h = 1080; } WebImage wi = new WebImage(@"~/img/" + fn); if (!h.HasValue) { Single ratio = (Single)wi.Width / (Single)wi.Height; h = (int)Math.Ceiling(w.Value / ratio); } wi .Resize(w.Value + 1, h.Value + 1, true, true) .Crop(1, 1) .Write(); } catch { var context = HttpContext.Current; // 拼接正确的根相对URL,处理网站在根目录时的特殊情况 string defaultImageUrl = context.Request.ApplicationPath + "/img/default.jpg"; if (defaultImageUrl.StartsWith("//")) { defaultImageUrl = defaultImageUrl.Substring(1); } context.Response.Redirect(defaultImageUrl, endResponse: true); } }
额外提示:
- 我修正了你原代码里的一个逻辑小问题:计算高度时,原代码用了
wi.Width / ratio,这会导致高度始终等于原图高度,应该用传入的w.Value来计算,才能实现按比例缩放的效果。 - 务必确保
~/img/default.jpg路径存在,否则会触发404错误。 endResponse: true参数会立即终止当前请求的处理,避免出现“已发送HTTP头后无法重定向”的异常。
内容的提问来源于stack exchange,提问作者Konstantin Sch
相关产品推荐
相关产品推荐

