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

Dan*_*per 0 c# routing generic-handler asp.net-mvc-2

也许我正在寻找错误的东西或试图以错误的方式实现这一点.我使用Generic Handler动态生成图像.我目前可以使用以下方式访问我

ImageHandler.ashx?width=x&height=y
Run Code Online (Sandbox Code Playgroud)

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

images/width/height/imagehandler
Run Code Online (Sandbox Code Playgroud)

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

干杯.

Dan*_*per 5

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

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

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

        return handler;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我实现了通用处理程序,创建了一个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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

然后你可以使用调用你的处理程序

<img src="/images/100/140/imagehandler.png" />
Run Code Online (Sandbox Code Playgroud)

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

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