Asp.net Web Api控制器操作通过Web配置设置授权 [英] Asp.net Web Api controller action authorize by web config settings
本文介绍了Asp.net Web Api控制器操作通过Web配置设置授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个控制器操作,我想通过Web配置设置使用可变授权.
I have a controller action and I want to use changeable authorization via web config settings.
public class ProductsController : ApiController
{
[HttpGet, Authorize]
public Product FindProduct(id) {}
}
<appSettings>
<add key="authorize" value="yes"/>
</appSettings>
推荐答案
您可以创建自己的 AuthorizeWithConfig
属性,该属性继承自 Authorize
属性:
You can create your own AuthorizeWithConfig
attribute that inherits from Authorize
attribute:
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);
}
}
然后您可以将其用于控制器操作:
Then you can use it for your controller actions:
public class ProductsController : ApiController
{
[HttpGet, AuthorizeWithConfig("App:RequireAuthorization")]
public Product FindProduct(id) {}
}
假设在应用程序设置中,您有一个 App:RequireAuthorization
设置,该设置采用布尔值:
Assuming that in app settings you have an App:RequireAuthorization
setting that takes boolean values:
<appSettings>
<add key="App:RequireAuthorization" value="false"/>
</appSettings>
这篇关于Asp.net Web Api控制器操作通过Web配置设置授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文