将服务注入动作过滤器 [英] Inject service into Action Filter

查看:31
本文介绍了将服务注入动作过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将服务注入到我的操作过滤器中,但我没有在构造函数中注入所需的服务.这是我所拥有的:

I am trying to inject a service into my action filter but I am not getting the required service injected in the constructor. Here is what I have:

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");
        }
    }
}

我正在装饰我的控制器:

And I am decorating my controller like so:

[Route("api/issues"), EnsureUserLoggedIn]
public class IssueController : Controller
{
}

Startup.cs

services.AddScoped<ISessionService, SessionService>();

推荐答案

使用这些文章作为参考:

Using these articles as reference:

ASP.NET Core 操作过滤器

ASP.NET 5 和 MVC 6 中的动作过滤器、服务过滤器和类型过滤器

将过滤器用作 ServiceFilter

因为过滤器将用作ServiceType,所以需要在框架IoC 中注册.如果直接使用操作过滤器,则不需要这样做.

Because the filter will be used as a ServiceType, it needs to be registered with the framework IoC. If the action filters were used directly, this would not be required.

Startup.cs

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc();

    services.AddScoped<ISessionService, SessionService>();
    services.AddScoped<EnsureUserLoggedIn>();

    ...
}

使用 ServiceFilter 属性将自定义过滤器添加到 MVC 控制器方法和控制器类,如下所示:

Custom filters are added to the MVC controller method and the controller class using the ServiceFilter attribute like so:

[ServiceFilter(typeof(EnsureUserLoggedIn))]
[Route("api/issues")]
public class IssueController : Controller {
    // GET: api/issues
    [HttpGet]
    [ServiceFilter(typeof(EnsureUserLoggedIn))]
    public IEnumerable<string> Get(){...}
}

还有其他

  • 使用过滤器作为全局过滤器

  • Using the filter as a global filter

在基本控制器中使用过滤器

Using the filter with base controllers

使用带订单的过滤器

看看,试一试,看看是否能解决您的问题.

Take a look, give them a try and see if that resolves your issue.

希望这会有所帮助.

这篇关于将服务注入动作过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆