在MVC中转发所有请求委托处理程序

时间:2016-06-28 07:33:23

标签: asp.net-mvc asp.net-web-api

我有一个用MVC编写的视图。我正在使用CustomRouteFilter的以下方法

捕获所有请求
public class CustomRoutesHandler : RouteBase
{
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        //my code
    }
}

在此,我想将所有请求转发给自定义DelegateHandler的{​​{1}}方法。谁能帮我。

SendAsync()

1 个答案:

答案 0 :(得分:0)

如果您可以从CustomRoutesHandler直接在RequestHandler上调用方法,那么以下工作:

<强> CustomRoutesHandler:

public class CustomRoutesHandler : RouteBase
{
    Route route;
    public CustomRoutesHandler(Route route)
    {
        this.route = route;
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        RequestHandler requestHandler = new RequestHandler();
        HttpRequestMessage request = new HttpRequestMessage();
        HttpResponseMessage response = requestHandler.SendAsync(request).Result;
        return route.GetRouteData(httpContext);
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        return route.GetVirtualPath(requestContext, values);
    }
}

<强> RequestHandler:

public class RequestHandler : DelegatingHandler
{
    public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
    {
        CancellationToken cancellationToken = CancellationToken.None;
        return SendAsync(request, cancellationToken);
    }
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        var tsc = new TaskCompletionSource<HttpResponseMessage>();
        tsc.SetResult(response); 
        return tsc.Task;
    }
}

<强> RouteConfig:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        Route route = routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        routes.Remove(route);
        routes.Add(new CustomRoutesHandler(route));
    }
}