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

时间:2016-01-08 07:54:42

标签: asp.net asp.net-web-api web-config

我有一个控制器操作,我想通过Web配置设置使用可更改的授权。

if let code = json["code"] as? Int { 
   if code == 200 {

   }
}

1 个答案:

答案 0 :(得分:0)

您可以创建自己的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>