gpt4 book ai didi

asp.net - 对每个请求执行代码

转载 作者:行者123 更新时间:2023-12-01 09:33:02 24 4
gpt4 key购买 nike

我需要运行一个验证例程,在对服务器的每个请求中查找一些 header 信息。我会使用 ASP.NET MVC 中的 OnActionExecuting 或 ActionInvoker 来处理每个请求,但我一直在寻找 Web API,但没有找到具体的东西。

如果可以同时实现同步和异步,那将是最好的。

最佳答案

对于 Web API,您应该使用 MessageHandlers

消息处理程序总是首先运行,在管道中的任何其他内容之前运行,并且它们也能够最后运行(在 Web API 返回响应之后,就在响应到达客户端之前)。

有关消息处理程序的更多信息可以在这里找到 - http://www.asp.net/web-api/overview/working-with-http/http-message-handlers .

下面是一个简单的例子,验证 API key :

public class WebApiKeyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string apikey = HttpUtility.ParseQueryString(request.RequestUri.Query).Get("apikey");
if (apikey != "something")
{
HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "You can't use the API without the key.");
throw new HttpResponseException(response);
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}

在此示例中,仅允许使用键“something”的请求:即/api/values/?apikey=something 将被允许,所有其他将被拒绝。

在您的情况下,您可以简单地访问 request.Headers 并验证您需要的任何内容。

关于asp.net - 对每个请求执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926043/

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