捕获对 Web Api 2.0 的所有请求,无论是否映射

Tam*_*nut 5 c# actionfilterattribute asp.net-web-api delegatinghandler

我有一个正在运行的 Web API 2.0 localhost:4512,我想拦截对域发出的所有请求,localhost:4512无论它们是否由特定路由处理。例如,我想捕获对localhost:4512/abc.dfsada或的请求localhost:4512/meh/abc.js

我已经使用 DelegatingHandler 尝试过此操作,但不幸的是,这只拦截对处理的路由发出的请求:

public class ProxyHandler : DelegatingHandler
{
    private async Task<HttpResponseMessage> RedirectRequest(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var redirectLocation = "http://localhost:54957/";
        var localPath = request.RequestUri.LocalPath;
        var client = new HttpClient();
        var clonedRequest = await request.Clone();
        clonedRequest.RequestUri = new Uri(redirectLocation + localPath);

        return await client.SendAsync(clonedRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return RedirectRequest(request, cancellationToken);
    }
}
Run Code Online (Sandbox Code Playgroud)

在 WebConfig.cs 中:

 config.MessageHandlers.Add(new ProxyHandler());
 config.MapHttpAttributeRoutes();
 config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new {id = RouteParameter.Optional});
Run Code Online (Sandbox Code Playgroud)

Mar*_*und 3

您可以使用Application_BeginRequestGlobal.asax 类中的当应用程序收到请求时将首先调用它

这是一个例子:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var request = ((System.Web.HttpApplication) sender).Request;
}
Run Code Online (Sandbox Code Playgroud)