【发布时间】:2016-07-06 15:56:13
【问题描述】:
我正在尝试将服务注入到我的操作过滤器中,但我没有在构造函数中注入所需的服务。这是我所拥有的:
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
{
}
Startup.cs
services.AddScoped<ISessionService, SessionService>();
【问题讨论】:
-
属性装饰只允许常量值。我想你应该在默认构造函数中解析你的服务。
-
我不确定在这种情况下怎么可能。
-
看这里,我猜你只需要一个decorator
-
不要尝试将服务注入属性,而是写passive attributes。
-
您不应该为授权/策略实现自己的过滤器或授权属性。这就是
AuthoirzeAttribute的策略生成器和策略属性。请参阅负责 ASP.NET Core 安全部分的 ASP.NET 开发人员的回答 stackoverflow.com/a/31465227/455493
标签: c# asp.net-core dependency-injection .net-core