簡體   English   中英

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

[英]C# ASP.NET MVC2 Routing Generic Handler

也許我在搜索錯誤的東西,或試圖以錯誤的方式實施此操作。 我正在使用通用處理程序動態生成圖像。 我目前可以使用以下命令訪問處理程序:

ImageHandler.ashx?width=x&height=y

我寧願使用類似的東西訪問我的處理程序

images/width/height/imagehandler

這可能是我在Google上發現的一些示例不適用於MVC2嗎?

干杯。

昨晚我繼續解決這個問題,令我驚訝的是,我已經接近我所想到的解決方案。 對於將來可能對此感到困擾的任何人,這里都是我實現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" />

我在需要時使用通用處理程序生成動態水印。 希望這可以幫助其他人。

如果您有任何疑問,請告訴我,我們將盡力為您提供幫助。

我已經使用該解決方案很長時間了,您可以使其通用,這樣它將接受將來使用的所有處理程序:

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>()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM