0

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

ImageHandler.ashx?width=x&height=y

我宁愿使用类似的东西访问我的处理程序

images/width/height/imagehandler

这可能是我在谷歌上找到的几个例子不适用于 MVC2。

干杯。

4

2 回答 2

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" />

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

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

于 2010-10-31T00:52:10.113 回答
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>()));
于 2015-03-20T17:00:24.477 回答