我将网站升级为使用传统 ASP.Net Web 表单中的 ASP.Net MVC。我使用 MVC 路由将对旧 .aspx 页面的请求重定向到新的控制器/操作等效项:
routes.MapRoute(
"OldPage",
"oldpage.aspx",
new { controller = "NewController", action = "NewAction", id = "" }
);
这对于页面来说非常有用,因为它们直接映射到控制器和操作。但是,我的问题是图像请求 - 我不知道如何重定向这些传入请求。
我需要重定向传入的请求http://www.domain.com/graphics/image.png to http://www.domain.com/content/images/image.png.
使用时正确的语法是什么.MapRoute()
method?
您无法使用 MVC 框架“开箱即用”地做到这一点。请记住,路由和 URL 重写之间存在差异。路由就是将每个请求映射到一个资源,而期望的资源就是一段代码。
然而,MVC 框架的灵活性允许您毫无问题地执行此操作。默认情况下,当您调用routes.MapRoute()
,它正在使用一个实例处理请求MvcRouteHandler()
。你可以建立一个custom处理程序来处理您的图像网址。
创建一个类,可能称为 ImageRouteHandler,它实现IRouteHandler
.
-
将映射添加到您的应用程序中,如下所示:
routes.Add("ImagesRoute", new Route("graphics/{filename}",
new ImageRouteHandler()));
就是这样。
这就是你的IRouteHandler
类看起来像:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;
namespace MvcApplication1
{
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string filename = requestContext.RouteData.Values["filename"] as string;
if (string.IsNullOrEmpty(filename))
{
// return a 404 HttpHandler here
}
else
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString());
// find physical path to image here.
string filepath = requestContext.HttpContext.Server.MapPath("~/test.jpg");
requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();
}
return null;
}
private static string GetContentType(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return "Image/bmp";
case ".gif": return "Image/gif";
case ".jpg": return "Image/jpeg";
case ".png": return "Image/png";
default: break;
}
return "";
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)