如何在IAuthenticationFilter实现中设置WWW-Authentication标头?

我正在使用MVC5的IAuthenticationFilter接口实现基本身份validation。 我的理解是,现在这是首选方法,而不是使用DelegatingHandler。 我已经开始工作,但响应中没有返回www-authenticate标头。 这是我对ChallengeAsync的实现:

public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { var result = await context.Result.ExecuteAsync(cancellationToken); if (result.StatusCode == HttpStatusCode.Unauthorized) { result.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=localhost")); } } 

如果我在AuthenticateAsync中设置它,则会返回标头,但我认为我应该在ChallengeAsync中设置它。 示例实现很难找到。

ChallengeAsync ,将context.Result设置为IHttpActionResult类型的实例,就像这样。

 public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { context.Result = new ResultWithChallenge(context.Result); return Task.FromResult(0); } 

像这样提供实现。

 public class ResultWithChallenge : IHttpActionResult { private readonly IHttpActionResult next; public ResultWithChallenge(IHttpActionResult next) { this.next = next; } public async Task ExecuteAsync( CancellationToken cancellationToken) { var response = await next.ExecuteAsync(cancellationToken); if (response.StatusCode == HttpStatusCode.Unauthorized) { response.Headers.WwwAuthenticate.Add( new AuthenticationHeaderValue("Basic", "realm=localhost")); } return response; } }