开发者

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 fac开发者_StackOverflow中文版t 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

  • Is it a bad idea to use ASP.NET MVC routing in this situation instead of URL rewriting?
  • What handler does IIS 7.0 routes requests to physical files?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜