我有一个用MVC编写的视图。我正在使用CustomRouteFilter
的以下方法
public class CustomRoutesHandler : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
//my code
}
}
在此,我想将所有请求转发给自定义DelegateHandler
的{{1}}方法。谁能帮我。
SendAsync()
答案 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));
}
}