[英]ASP.Net Core 2.2 - Method overload appears in Visual Studio but does not work at run-time
我正在尝试验证用户是否通过自定义策略获得授权。 我按照Ode To Code 中的教程将此功能添加到我的控制器中。 在 Visual Studio 中,代码似乎是正确的,并且使用了已知的重载。
请注意,它说重载是一个“扩展”。 直到今天我花了 5 个小时试图解决以下错误,我才注意到这一点:
如您所见,我尝试使用的重载似乎没有被利用。 我在这里做错了吗? 为了包含这些扩展方法,我需要做什么特别的事情吗? 我已经尝试清理和重建解决方案,但这并没有解决问题。
虽然您已经为IAuthorizationSerivce
定义了字段, IAuthorizationSerivce
您还没有提供任何设置方法。 您需要定义的构造LRController
,它利用一个参数IAuthorizationService
,并分配到外地。
我认为教程中有该构造函数的定义。
请注意名称更改:例如 IAuthorizationService _authorization
的全局变量名称已以下划线作为前缀。 显然不是必需的,但作为一个很好的经验法则/良好的编码标准,IMO。 :-)
public class LRController : Controller
{
private readonly IAuthorizationService _authorization;
// you're missing this constructor & this pattern is known as Constructor Dependency Injection
public LRController(IAuthorizationService authorization)
{
_authorization = authorization;
}
public async Task<RedirectToActionResult> Index()
{
var superAdmin = await _authorization.AuthorizeAsync(User, "IsLucky");
//rest of your code here
}
}
编辑
此外,如果您想/需要将其他接口注入该控制器,您可以将其添加到该 LRController 构造函数中。 看起来像这样:
public class LRController : Controller
{
private readonly IAuthorizationService _authorization;
private readonly IOtherService _otherService;
public LRController(IAuthorizationService authorization, IOtherService otherService)
{
_authorization = authorization;
_otherService = otherService;
}
public async Task<RedirectToActionResult> Index()
{
var superAdmin = await _authorization.AuthorizeAsync(User, "IsLucky");
}
public async Task Foo()
{
await _otherService.Bar();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.