用于图像大小调整的MVC3通用处理程序(.ashx)(需要干净的URL)

时间:2013-07-23 13:28:02

标签: asp.net-mvc-3 url-rewriting httpcontext generic-handler

我在asp.net mvc3 web应用程序中有一个通用处理程序(.ashx)。我用它来调整大小和缓存图像。但是我的网址不干净(http://www.example.com/Thumb.ashx?img=someimage.jpg)我希望像http://www.example.com/Thumb/someimage.jpg一样干净 我怎么能这样做?

我可以在global.asax中进行maproute,是吗?或者我应该使用IIS 7 URL重写?

我感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:3)

经过几个小时的研究后,我使用了类(RouteHandler.cs)http处理程序,但没有使用.ashx,因为.ashx不能使用global.asax进行路由

public class RouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        HttpHanler httpHandler = new HttpHanler();
        return httpHandler;
    }
    public class HttpHanler : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            var routeValues = context.Request.RequestContext.RouteData.Values;
            string file = context.Request.RequestContext.RouteData.Values["img"].ToString();

            // anything you can do here.

             context.Response.ContentType = "image/jpeg";
             context.Response.BinaryWrite("~/cat.jpg");
             context.Response.End();

        }
    }
}

然后在global.asax中注册路线

 routes.Add(new Route("Thumb/{img}", new RouteHandler()));
相关问题