且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-31 17:02:50

您不能这样做开箱即用的MVC框架。记得有路由和URL重写之间的差。路由映射每个请求的资源,和预期的资源是一块code的。

You can't do this "out of the box" with the MVC framework. Remember that there is a difference between Routing and URL-rewriting. Routing is mapping every request to a resource, and the expected resource is a piece of code.

不过 - MVC框架的灵活性,可以让你没有真正的问题,做到这一点。默认情况下,当你调用 routes.MapRoute(),它的操控性与的一个实例,要求MvcRouteHandler()。你可以建立一个的自定义的处理程序来处理图像的URL。

However - the flexibility of the MVC framework allows you to do this with no real problem. By default, when you call routes.MapRoute(), it's handling the request with an instance of MvcRouteHandler(). You can build a custom handler to handle your image urls.


  1. 创建一个类,也许叫ImageRouteHandler,实现 IRouteHandler

映射添加到您的应用程序是这样的:

Add the mapping to your app like this:

routes.Add(ImagesRoute,新干线(图形/ {文件名},结果
           新ImageRouteHandler()));

这就是它。

这是你的 IRouteHandler 类看起来是这样的:

Here's what your IRouteHandler class looks like:

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 "";
        }
    }
}