gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:01:57 24 4
gpt4 key购买 nike

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

的请求

我已经用 DelegatingHandler 试过了,但是 unfortunately这只会拦截对已处理路由的请求:

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

在 WebConfig.cs 中:

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

最佳答案

您可以在 Global.asax 类中使用 Application_BeginRequest 方法。当应用程序收到请求时,它会首先被调用

这是一个例子:

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

关于c# - 捕获对 Web Api 2.0 的所有请求,无论是否已映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50748937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com