THX-1138
THX-1138

Reputation: 21740

asp.net mvc 2.0 : route request to static resource

I want to route HTTP requests not to an action, but to a file.

Important: I do have a working solution using IIS 7.0 URL Rewriting module, but for debugging at home (no IIS 7.0) I can't use URL rewriting.

Specific situation
I want to point any URL that contains /images/ to a ~/images/ folder.

Example:

http://wowreforge.com/images/a.png -> /images/a.png
http://wowreforge.com/Emerald Dream/Jizi/images/a.png -> /images/a.png
http://wowreforge.com/US/Emerald Dream/Jizi/images/a.png -> /images/a.png
http://wowreforge.com/characters/view/images/a.png -> /images/a.png

The problem stems from the fact that page "view_character.aspx" can be arrived to from multiple URLs:

http://wowreforge.com/?name=jizi&reaml=Emerald Dream
http://wowreforge.com/US/Emerald Dream/Jizi

Context IIS 7.0 (integrated mode), ASP.NET MVC 2.0

Extra Credit Questions

Upvotes: 3

Views: 1355

Answers (1)

Vadim
Vadim

Reputation: 17955

You should probably rewrite your links to images to.

<img src="<%= ResolveUrl("~/images/a.png") %>" />

That way you don't need to have your routes handle the images.

UPDATE How you would do it through routing add this entry to your RouteTable

routes.Add("images", new Route("{*path}", null, 
   new RouteValueDictionary(new { path = ".*/images/.*"}), 
   new ImageRouteHandler()));

Now you need to create an ImageRouteHandler and an ImageHandler

public class ImageRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        //you'll need to figure out how to get the physical path
        return new ImageHandler(/* get physical path */);
    }
}

public class ImageHandler : IHttpHandler
{
    public string PhysicalPath { get; set; }

    public ImageHandler(string physicalPath)
    {
        PhysicalPath = physicalPath;
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.TransmitFile(PhysicalPath);
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

This also doesn't do any caching. You can check out System.Web.StaticFileHandler in Reflector for the handler that processes static files for an Asp.Net application for a more complete implementation.

Upvotes: 3

Related Questions