Asp.net Web Api 控制器操作通过 Web 配置设置授权

Asp.net Web Api controller action authorize by web config settings

我有一个控制器操作,我想通过网络配置设置使用可变授权。

public class ProductsController : ApiController
{
    [HttpGet, Authorize]
    public Product FindProduct(id) {}
}   

<appSettings>
  <add key="authorize" value="yes"/>
</appSettings>

您可以创建自己的 AuthorizeWithConfig 属性,该属性继承自 Authorize 属性:

public class AuthorizeWithConfigAttribute : AuthorizeAttribute
{
    private readonly string _configKey;

    public AuthorizeWithConfigAttribute(string configKey)
    {
        _configKey = configKey;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        // Will be read from configuration
        bool requireAuthorization;

        // Skip authorization if
        // (1) Found the specified key in app settings
        // (2) Could parse app setting value into a boolean
        // (3) App setting value is set to FALSE
        var skipAuthorization =               
            ConfigurationManager.AppSettings.ContainsKey(configKey) 
            && bool.TryParse(ConfigurationManager.AppSettings[configKey],
                             out requireAuthorization) 
            && !requireAuthorization;

        return skipAuthorization ? true : base.IsAuthorized(actionContext);
    }
}

然后您可以将它用于您的控制器操作:

public class ProductsController : ApiController
{
    [HttpGet, AuthorizeWithConfig("App:RequireAuthorization")]
    public Product FindProduct(id) {}
}

假设您在应用程序设置中有一个采用布尔值的 App:RequireAuthorization 设置:

<appSettings>
  <add key="App:RequireAuthorization" value="false"/>
</appSettings>