C#ASP.NET MVC2路由通用处理程序

时间:2010-10-30 12:20:42

标签: c# asp.net-mvc-2 routing generic-handler

也许我正在寻找错误的东西或试图以错误的方式实施。我使用Generic Handler动态生成图像。我现在可以使用以下方式访问我的处理程序:

ImageHandler.ashx?width=x&height=y

我更愿意使用像

这样的东西来访问我的处理程序
images/width/height/imagehandler

这可能是我在谷歌上找到的几个例子与MVC2不兼容。

干杯。

2 个答案:

答案 0 :(得分:5)

昨晚我继续研究这个问题,令我惊讶的是,我更接近我想到的解决方案。对于今后可能会遇到这种情况的人来说,我是如何将MVC2路由实现为通用处理程序的。

首先,我创建了一个继承了IRouteHandler

的类
public class ImageHandlerRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var handler = new ImageHandler();
        handler.ProcessRequest(requestContext);

        return handler;
    }
}

然后我实现了通用处理程序,创建了一个MVC友好的ProcessRequest。

public void ProcessRequest(RequestContext requestContext)
{
    var response = requestContext.HttpContext.Response;
    var request = requestContext.HttpContext.Request;

    int width = 100;
    if(requestContext.RouteData.Values["width"] != null)
    {
        width = int.Parse(requestContext.RouteData.Values["width"].ToString());
    }

    ...

    response.ContentType = "image/png";
    response.BinaryWrite(buffer);
    response.Flush();
}

然后添加了一个到global.asax的路由

RouteTable.Routes.Add(
    new Route(
        "images/{width}/{height}/imagehandler.png", 
        new ImageShadowRouteHandler()
    )
 );

然后你可以使用

调用你的处理程序
<img src="/images/100/140/imagehandler.png" />

我使用通用处理程序在需要时生成动态水印。希望这有助于其他人。

如果您有任何问题,请告诉我,我会尽可能帮助您。

答案 1 :(得分:0)

我现在使用该解决方案很长一段时间了,你可以使它成为通用的,这样它就会接受你将来拥有的任何处理程序:

internal class RouteGenericHandler<T> : IRouteHandler where T : IHttpHandler, new()
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new T();
    }
}

在RegisterRoutes方法上:

routes.Add(new Route("Name", new RouteGenericHandler<TestHandler>()));