相关疑难解决方法(0)

将服务注入Action Filter

我试图将一个服务注入我的动作过滤器,但我没有在构造函数中注入所需的服务.这是我有的:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

而我正在装饰我的控制器:

[Route("api/issues"), EnsureUserLoggedIn]
public class IssueController : …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection .net-core asp.net-core

55
推荐指数
5
解决办法
4万
查看次数

如何在ASP.NET CORE中使用具有依赖注入的动作过滤器?

我在我的ASP.NET CORE应用程序中使用基于构造函数的依赖注入,我还需要在我的动作过滤器中解决依赖关系:

public class MyAttribute : ActionFilterAttribute
{
    public int Limit { get; set; } // some custom parameters passed from Action
    private ICustomService CustomService { get; } // this must be resolved

    public MyAttribute()
    {
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // my code
        ...

        await next();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在控制器中:

[MyAttribute(Limit = 10)]
public IActionResult()
{
    ...
Run Code Online (Sandbox Code Playgroud)

如果我把ICustomService放到构造函数中,那么我就无法编译我的项目了.那么,我如何在动作过滤器中获取接口实例呢?

c# asp.net asp.net-mvc action-filter asp.net-core

14
推荐指数
3
解决办法
1万
查看次数

ServiceFilter和TypeFilter - 注入这些过滤器有什么区别?

ServiceFilter我们必须在Startup.cs中注册.TypeFilter是由Microsoft.Extensions.DependencyInjection.ObjectFactory注入的,我们不需要注册那个过滤器.

那么当我们应该使用ServiceFilter和TypeFilter时?

c# asp.net-core-mvc asp.net-core

10
推荐指数
3
解决办法
6074
查看次数