asp.net - 在asp.net core rc2应用程序的ActionFilterAttribute中访问IConfiguration

标签 asp.net asp.net-core

这个问题在这里已经有了答案:





Inject service into Action Filter

(6 个回答)


5年前关闭。




我正在编写将验证验证码的属性。为了正常工作,它需要知道我保存在设置中的 secret ( secret 管理器工具)。但是我不知道如何从属性类中读取配置。 asp.net core中的DI支持构造函数注入(inject)(不支持属性注入(inject)),所以会报编译错误:

public ValidateReCaptchaAttribute(IConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.m_configuration = configuration;
        }

因为当我用 [ValidateReCaptcha] 装饰方法时我无法通过配置

那么如何从属性类中的方法中读取配置中的内容呢?

最佳答案

您可以使用 ServiceFilter attribute ,更多信息在此blog postasp.net docs .

[ServiceFilter(typeof(ValidateReCaptchaAttribute))]
public IActionResult SomeAction()

Startup
public void ConfigureServices(IServiceCollection services)
{
       // Add functionality to inject IOptions<T>
       services.AddOptions();

       // Add our Config object so it can be injected
       services.Configure<CaptchaSettings>(Configuration.GetSection("CaptchaSettings"));

       services.AddScoped<ValidateReCaptchaAttribute>();
       ...
}

ValidateReCaptchaAttribute
public class ValidateReCaptchaAttribute : ActionFilterAttribute
{
     private readonly CaptchaSettings _settings;

     public ValidateReCaptchaAttribute(IOptions<CaptchaSettings> options)
     {
         _settings = options.Value;
     }

     public override void OnActionExecuting(ActionExecutingContext context)
     {
         ...
         base.OnActionExecuting(context);
     }
}

关于asp.net - 在asp.net core rc2应用程序的ActionFilterAttribute中访问IConfiguration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37876035/

相关文章:

c# - 无法识别的元素 'authentication' 。

c# - 该名称在当前上下文中不存在

c# - 无法将字符串转换为 TimeSpan

Asp.Net 核心 : Add data to IdentityDbContext or use DbContext

c# - .net 核心注册通用接口(interface)并使用 getservice 检索它们

c# - 尝试将 SMTP 与 gmail 一起使用

asp.net - 我们如何确定我们使用的是 Web API 1 还是 Web API 2?

c# - 在 LINQ 中更新对象

c# - 将 'hd' 参数附加到 redirectUrl ASP.NET Core 1 with Identity 3

c# - 网络核心 : Use memory cache outside controller