C# Web API中的自定义IAAuthenticationFilter和AllowAnonymous

C# Web API中的自定义IAAuthenticationFilter和AllowAnonymous,c#,authentication,asp.net-web-api2,custom-attributes,C#,Authentication,Asp.net Web Api2,Custom Attributes,我想使用AllowAnonymous和自定义AuthenticationFilter。有人能给我指出正确的方向来使用AllowAnonymous或其他替代方法吗?谢谢 我创建了自己的自定义筛选器,该筛选器继承自System.Attribute,并实现System.Web.Http.Filters.iaAuthenticationFilter 公共类MyCustomAuthenticationAttribute:属性,IAAuthenticationFilter 我已经成功地为authentic

我想使用
AllowAnonymous
和自定义
AuthenticationFilter
。有人能给我指出正确的方向来使用
AllowAnonymous
或其他替代方法吗?谢谢

我创建了自己的自定义筛选器,该筛选器继承自
System.Attribute
,并实现
System.Web.Http.Filters.iaAuthenticationFilter

公共类MyCustomAuthenticationAttribute:属性,IAAuthenticationFilter
我已经成功地为
authenticateSync
方法添加了逻辑

public异步任务AuthenticateAsync(
HttpAuthenticationContext上下文,
CancellationToken CancellationToken){}
我的问题是,我需要忽略一些Web API控制器操作或控制器。我想我可以使用
System.Web.Http.AllowAnonymousAttribute
来实现这一点。例如,这里有一个显示意图的非常简单的示例

[MyCustomAuthentication]
公共类HomeController:ApiController
{
//无需身份验证,允许匿名
[HttpGet]
[路线(“hianonymous”)]
[异名]
公共IHttpActionResult Hello(字符串名称){
返回Ok(新的{message=“hello”+name});
}
//需要进行身份验证
[HttpGet]
[路线(“hiauthenticated”)]
公共IHttpActionResult Hello(){
var name=User.Identity.name;
返回Ok(新的{message=“hello authenticated user”+name});
}
}
问题是,
MyCustomAuthenticationAttribute
仍在调用
Authenticate()
。我想使用
AllowAnonymous
或其他方法来实现这一点。谢谢你的意见


我知道我可以在操作级别而不是控制器级别使用自定义身份验证属性,但有些情况下我希望使用整个控制器,甚至作为全局过滤器,因此我需要能够在单个操作或控制器的基础上排除

如果您的
iaauthenticationfilter
实现没有找到它无法识别的授权方案,那么它应该什么都不做

其思想是,您的过滤器只是一种使用已知方案进行身份验证的方法


您仍然需要使用内置的
AuthorizeAttribute
AllowAnonymousAttribute
来控制授权

作为参考,我在asp.net网站上使用了这个示例来开始这方面的工作。
// 2. If there are no credentials, do nothing.
if (authorization == null)
{
    return;
}

// 3. If there are credentials but the filter does not recognize the 
//    authentication scheme, do nothing.
if (authorization.Scheme != "Basic")
{
    return;
}