我正在尝试将服务注入到我的操作筛选器中,但是在构造函数中没有得到所需的服务注入。这是我的代码:
public class EnsureUserLoggedIn : ActionFilterAttribute
{
private readonly ISessionService _sessionService;
public EnsureUserLoggedIn()
{
// I was unable able to remove the default ctor
// because of compilation error while using the
// attribute in my controller
}
public EnsureUserLoggedIn(ISessionService sessionService)
{
_sessionService = sessionService;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
// Problem: _sessionService is null here
if (_sessionService.LoggedInUser == null)
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Result = new JsonResult("Unauthorized");
}
}
}
我正在像这样装饰我的控制器:
[Route("api/issues"), EnsureUserLoggedIn]
public class IssueController : Controller
{
}
启动.cs
services.AddScoped<ISessionService, SessionService>();
AuthorizeAttribute
的策略构建器和策略属性的作用。请参考这位负责ASP.NET Core安全部分的ASP.NET开发人员的答案:https://dev59.com/CVwZ5IYBdhLWcg3wbv7r#31465227 - Tseng