3

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

如果可以为同步和异步实现某些东西,那将是最好的。

4

1 回答 1

8

对于 Web API,您应该求助于MessageHandlers

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

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

这是一个简单的示例,验证 API 密钥:

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并验证您需要的任何内容。

于 2012-10-17T02:16:48.780 回答