利用DelegatingHandler实现webapi的key校验
ASP.NET Web API服务端框架由一组HttpMessageHandler经过“首尾相连”而成,管道式设计使该框架具有很高的扩展性。虽然ASP.NET Web API服务端框架的作用是“处理请求、响应回复”,但是具体采用的处理策略因具体的场景而不同。我们不可能也没有必要创建一个“万能”的处理器来满足所有的请求处理场景,所以倒不如让某个处理器只负责某个单一的消息处理功能。针对具体的应用场景中,我们可以根据具体的消息处理需求来选择所需的处理器并共同组成一个完成的消息处理管道。在这里这个用于完成某个单一消息处理功能的处理器就是HttpMessageHandler。
HttpMessageHandler是抽象类,DelegatingHandler是它的派生类
编写ApiKeyHandler
public class ApiKeyHandler : DelegatingHandler
{
public string Key { get; set; }
public ApiKeyHandler(string key,HttpConfiguration httpConfiguration)
{
this.Key = key;
InnerHandler = new HttpControllerDispatcher(httpConfiguration);
}
protected override Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!ValidateKey(request))
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
var tsc = new TaskCompletionSource();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
private bool ValidateKey(HttpRequestMessage message)
{
IEnumerable<string> apiKeyHeaderValues = null;
if (message.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
{
var apiKeyHeaderValue = apiKeyHeaderValues.First();
return (apiKeyHeaderValue == this.Key)
// ... your authentication logic here ...
/*
var username = (apiKeyHeaderValue == "00000" ? "Maarten" : "OtherUser");
var usernameClaim = new Claim(ClaimTypes.Name, username);
var identity = new ClaimsIdentity(new[] { usernameClaim }, "ApiKey");
var principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
*/
}
/*
var query = message.RequestUri.ParseQueryString();
string key = query["key"];
return (key == this.Key);
*/
}
配置到特定的路由上去
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new ApiKeyHandler("12345", GlobalConfiguration.Configuration)
);
参考:
https://blog.csdn.net/dyllove98/article/details/9707507
https://www.cnblogs.com/ywolf123/p/5340938.html