我正在尝试编写一个自定义 IHttpHandler 来验证调用 ASP.NET Web API 应用程序的用户:
public class AuthenticationHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
var id = context.Request.QueryString["id"];
if (String.IsNullOrWhiteSpace(id))
{
return;
}
var key = context.Request.QueryString["key"];
if (String.IsNullOrWhiteSpace(key))
{
return;
}
using (var db = new DataContext())))
{
var client = db.Clients.FirstOrDefault(x => x.ApiId == id);
if (client == null)
{
return;
}
if (!client.ApiKeys.Any(x => x.Key == key))
{
return;
}
context.User = new ApiPrincipal
{
Identity = new ApiIdentity
{
IsAuthenticated = true,
Name = client.Name,
ClientId = client.Id
}
};
Thread.CurrentPrincipal = context.User;
}
}
}
我的 Web.config 部分如下所示:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="AuthenticationHandler" path="*" verb="*" type="AuthenticationHandler" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
AuthenticationHandler 是我的自定义处理程序。它确实可以在根页面上工作,即http://example.com/,但不能在其他页面上工作。如果指定了任何路由,即http://example.com/MyApiController,则永远不会运行 ProcessRequest。
感谢您的关注!