我有一个动态工作的图像大小调整功能。可以说,如果实际图像在服务器上可用并且不存在其不同大小(中,小)。Application_error 捕获并重定向到 ErrorController,在此调整大小并返回新创建的图像文件,状态为 200 而不是 404
这适用于 Visual Studio 2012,但一旦部署在 IIS 7.5 上,它就会停止工作。我将 Application_Error 和 ErrorController 代码放在这里
protected void Application_Error(object sender, EventArgs e)
{
var app = (MvcApplication)sender;
var context = app.Context;
var filePath = ((System.Web.HttpApplication)(app)).Request.FilePath;
var ex = app.Server.GetLastError();
context.Response.Clear();
context.ClearError();
var httpException = ex as HttpException;
var routeData = new RouteData();
routeData.Values["controller"] = "errors";
routeData.Values["exception"] = ex;
routeData.Values["action"] = "http500";
routeData.Values["id"] = filePath;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values["action"] = "http404";
break;
case 403:
routeData.Values["action"] = "http403";
break;
case 500:
routeData.Values["action"] = "http500";
break;
}
}
IController controller = new JewelryPotSite.Controllers.ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
}
错误控制器代码是
公共 ActionResult Http404(字符串 id)
{
bool flag = false;
if (id.ToLower().Contains("/thumbnail/"))
{
flag = true;
string actualFilePath = id.ToLower().Replace("/thumbnail", "");
string test = Server.MapPath(actualFilePath);
if (System.IO.File.Exists(Server.MapPath(actualFilePath)))
{
if (!System.IO.File.Exists(Server.MapPath(id)))
{
Bitmap mg = new Bitmap(Server.MapPath(actualFilePath));
ResizeImage(mg, id, new Size(56, 56));
Response.StatusCode = 200;
}
}
else
{
Response.StatusCode = 404;
return Content("404", "text/plain");
}
}
if (id.ToLower().Contains("/medium/"))
{
flag = true;
string actualFilePath = id.ToLower().Replace("/medium", "");
string test = Server.MapPath(actualFilePath);
if (System.IO.File.Exists(Server.MapPath(actualFilePath)))
{
if (!System.IO.File.Exists(Server.MapPath(id)))
{
Bitmap mg = new Bitmap(Server.MapPath(actualFilePath));
ResizeImage(mg, id, new Size(250, 250));
Response.StatusCode = 200;
}
}
else
{
Response.StatusCode = 404;
return Content("404", "text/plain");
}
}
if (flag == false)
{
Response.StatusCode = 404;
ViewBag.Message = 404;
return View("Error");
}
return File(id, "image/JPEG");
//return Content("404", "text/plain");
}