Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c# - How can I use await within an override of HandleRequirementAsync

I'm writing my own Authorisation handler that needs to do async work inside so that it can read the body of an incoming request and check some details.

However it falls down at the use of the await keyword. I need to be able to use await so that I can ensure the body is read from the request. If I don't use await and instead use ContinueWith, the execution falls through to one of the context.Fail() actions, and the request is denied with a 401 return.

However if I include the await and make the method async then I start getting compiler errors when I try to return Task.CompletedTask with the message Return type is void.

What do I need to change here?

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, DeviceJwtAuthorisationRequirement requirement)
        {
            if(_httpContextAccessor != null)
            {
                if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue("Authorization", out var authorizationHeader))
                {
                    var providedApiKey = authorizationHeader.FirstOrDefault();
                    var elements = providedApiKey.Split(" ");
                    var request = _httpContextAccessor.HttpContext.Request;
                    if(request.Body != null)
                    {
                        _httpContextAccessor.HttpContext.Request.EnableBuffering();
                        var body = request.Body;
                        var buffer = new byte[Convert.ToInt32(request.ContentLength)];
                        await request.Body.ReadAsync(buffer, 0, buffer.Length);
                       
                        //Check details and context.Succeed(requirement);
                    }
                    context.Fail();
                    return Task.CompletedTask;
                }
            }
            context.Fail();
            return Task.CompletedTask;
        }
question from:https://stackoverflow.com/questions/66048347/how-can-i-use-await-within-an-override-of-handlerequirementasync

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...