扩展“ApiExplorerSettingsAttribute”类看起来很简单,但它是密封的。所以最终得到了以下解决方法;
IncludeInApiExplorerAttribute.cs 类
public class IncludeInApiExplorerAttribute : Attribute
{
private readonly bool value;
public IncludeInApiExplorerAttribute(string IsInAPI=null)
{
if (!string.IsNullOrEmpty(IsInAPI))
{
value = Convert.ToBoolean(ConfigurationManager.AppSettings[IsInAPI]); //Reads the app config value
}
else
{
value = true;
}
}
public bool Value { get { return value; } }
}
- 然后我们可以实现一个自定义的 ApiExplorer,如下所示。
OptApiExplorer.cs 类
public class OptApiExplorer : ApiExplorer
{
public OptApiExplorer(HttpConfiguration configuration)
: base(configuration)
{
}
//Overrides the method from the base class
public override bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)
{
var includeAttribute = actionDescriptor.GetCustomAttributes<IncludeInApiExplorerAttribute>().FirstOrDefault(); //Get the given custom attribute from the action
if (includeAttribute != null)
{
return includeAttribute.Value && MatchRegexConstraint(route, "action", actionVariableValue); //If it is not null read the includeAttribute.Value which is set in app.config and return true or false based on the includeAttribute.Value and MatchRegexConstraint return value
}
var includeControlAttribute = actionDescriptor.ControllerDescriptor.GetCustomAttributes<IncludeInApiExplorerAttribute>().FirstOrDefault(); //If the action does not have any given type of custom attribute then chekc it in the controller level
if (includeControlAttribute != null)
{
return includeControlAttribute.Value && MatchRegexConstraint(route, "action", actionVariableValue);//Similar to action level
}
return true && MatchRegexConstraint(route, "action", actionVariableValue);
}
//This method is as it is in the base class
private static bool MatchRegexConstraint(IHttpRoute route, string parameterName, string parameterValue)
{
IDictionary<string, object> constraints = route.Constraints;
if (constraints != null)
{
object constraint;
if (constraints.TryGetValue(parameterName, out constraint))
{
string constraintsRule = constraint as string;
if (constraintsRule != null)
{
string constraintsRegEx = "^(" + constraintsRule + ")$";
return parameterValue != null && Regex.IsMatch(parameterValue, constraintsRegEx, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
}
}
}
return true;
}
}
这是我们的自定义属性读取的值。将此添加到 web.config 文件中
<appSettings>
<add key="IsInAPI" value="false"/>
</appSettings>
- 在 WebAPI.config.cs 文件中添加以下内容
我们已经用自定义类替换了 IApiExplorer。
config.Services.Replace(typeof(IApiExplorer), new OptApiExplorer(config));
-
然后在你的控制器或动作中你可以添加自定义
属性如下。
[IncludeInApiExplorer("IsInAPI")]
IsInApi 是 web.config 的值,我们可以设置为 true 或 false。如果未设置,则默认设置为 true,就像我们在 IncludeInApiExplorerAttribute 类中实现的那样。
请参阅此post 了解更多信息。