相关疑难解决方法(0)

在身份验证过滤器中的ChallengeAsync方法的上下文中设置结果

这个问题与我在这里提供的答案有关.OP的评论让我思考了一下.我建议在身份验证过滤器IHttpActionResultChallengeAsync方法中使用类似这样的类.

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<HttpResponseMessage> 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是这个,我可以简化ChallengeAsync这个.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                             CancellationToken cancellationToken)
{
    var result = await context.Result.ExecuteAsync(cancellationToken); …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api asp.net-mvc-5 asp.net-web-api2

6
推荐指数
1
解决办法
6961
查看次数