我有一个控制器操作,我想通过Web配置设置使用可更改的授权。
if let code = json["code"] as? Int {
if code == 200 {
}
}
答案 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>