小编典典

如何使用ASP.Net MVC路由来路由图像?

c#

我将网站升级为使用来自传统ASP.Net Web表单的ASP.Net MVC。我正在使用MVC路由将旧.aspx页的请求重定向到其新的Controller
/ Action等效项:

        routes.MapRoute(
            "OldPage",
            "oldpage.aspx",
            new { controller = "NewController", action = "NewAction", id = "" }
        );

这对于页面非常有效,因为它们直接映射到控制器和操作。但是,我的问题是图像请求-我不确定如何重定向这些传入请求。

我需要将http://www.domain.com/graphics/image.png的传入请求重定向到http://www.domain.com/content/images/image.png

使用该.MapRoute()方法时正确的语法是什么?


阅读 348

收藏
2020-05-19

共1个答案

小编典典

您不能使用MVC框架“开箱即用”执行此操作。请记住,路由和URL重写之间是有区别的。路由将每个请求映射到一个资源,而预期的资源就是一段代码。

但是,MVC框架的灵活性使您可以毫无问题地完成此操作。默认情况下,调用时routes.MapRoute(),它将使用的实例处理请求MvcRouteHandler()。您可以构建
自定义 处理程序来处理图像网址。

  1. 创建一个实现的类(可能称为ImageRouteHandler)IRouteHandler

  2. 将映射添加到您的应用中,如下所示:

routes.Add("ImagesRoute", new Route("graphics/{filename}", new ImageRouteHandler()));

  1. 而已。

这是您的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 "";
        }
    }
}
2020-05-19