您不能使用MVC框架"开箱即用"完成这项工作.请记住,路由和URL重写之间是有区别的.路由是将每个请求映射到资源,而预期的资源是一段代码.
然而,MVC框架的灵活性使您可以毫无问题地完成这项工作.默认情况下,当您调用routes.MapRoute()
时,它将使用MvcRouteHandler()
实例处理请求.您可以构建一个custom处理程序来处理图像URL.
创建一个类,可能称为ImageRouteHandler,它实现了IRouteHandler
.
将 map 添加到您的应用程序,如下所示:
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 "";
}
}
}