Bri*_*ins 3 asp.net asp.net-web-api
我需要运行一个验证例程,查找每个服务器请求的头信息.我会在ASP.NET MVC或ActionInvoker中使用OnActionExecuting来运行每个请求,但我一直在寻找Web API,并没有找到具体的东西.
如果可以同步和异步实现某些功能,那将是最好的.
对于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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,仅使用键"something"进行请求:即/ api/values /?apikey =将允许某些内容,所有其他内容将被拒绝.
在您的情况下,您只需访问request.Headers并验证您需要的任何内容.
| 归档时间: |
|
| 查看次数: |
427 次 |
| 最近记录: |