How do I route images through ASP.NET routing?

后端 未结 5 1254
一生所求
一生所求 2021-02-09 07:31

I\'d like to create a dynamic thumbnail resizer so that you can use the following URL to get a resized image:

http://server/images/image.jpg?width=320&height         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-09 07:52

    You could also consider:

    1. Writing a Module to handle these image routes before it hits routing (registered in Web.Config)
    2. Write your own route handler specifically to handle these images.

    Both would allow you to remove the need to write as a controller, I think this is cleaner.

    Very basic example of your own route handler (from memory)...

    Register as a normal route:

    /* Register in routing */
    routes.Add("MyImageHandler",
               new Route("my-custom-url/{folder}/{filename}", 
               new ImageRouteHandler())
    );
    
    
    /* Your route handler */
    public class ImageRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            string filename = requestContext.RouteData.Values["filename"] as string;
            string folder = requestContext.RouteData.Values["folder"] as string;
            string width = requestContext.HttpContext.Request.Params["w"] as string;
            string height = requestContext.HttpContext.Request.Params["h"] as string;
    
            // Look up the file and handle and return, etc...
        }
    }
    

    Hope these help. Lots of ways to extend and achieve :)

提交回复
热议问题