如何解决在 AuthorizationHandler
我有一个 AuthorizationHandler 依赖于为 .NET Core 3.1 的授权中间件提供异步方法的服务。我在 HandleRequirementAsync
方法中调用了其中一些异步方法。整体代码如下所示:
{
public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement,Tuple<string,string>>
{
private readonly IAuthIntelRepository authIntelRepository;
public UserAssistanceAuthorizationHandler(IAuthIntelRepository authIntelRepository)
{
this.authIntelRepository = authIntelRepository;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,MyRequirement requirement,string> someRessource)
{
//some async calls to authIntelRepository
if (/*someCondition*/false)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public class MyRequirement : IAuthorizationRequirement { }
}
虽然我很快使用了 await
语句,但我收到一个错误,指出签名未明确设置为异步。将 async
添加到继承方法的签名会导致以下错误。
a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'?
This thread 阐述了一个类似的问题,但该解决方案似乎在 .NET Core 3.1 中不起作用。
以下列方式使用 Result 有效,但 AFAIK 这将导致阻塞调用:
Task<Object> obj= this.authIntelRepository.getSomeAsync(...);
obj.Result.property //do Something to check the requirement
我不确定这里的正确解决方案是什么样的。
解决方法
如果您的 async
方法的返回类型是 Task
,那么,除了 await
关键字,您将您的方法视为 void
返回:
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,MyRequirement requirement,Tuple<string,string> someRessource)
{
await authIntelRepository....
if (/*someCondition*/false)
{
context.Succeed(requirement);
}
return;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。