我需要通过单独的授权规则列表来保护我的业务对象属性。我希望在各种操作期间暂停我的授权规则,例如转换为 DTO 和执行验证规则(验证当前用户无权查看的属性值)。
我正在研究的方法将调用包装在一个范围对象中,该对象使用 [ThreadStatic] 属性来确定是否应该运行授权规则:
public class SuspendedAuthorizationScope : IDisposable
{
[ThreadStatic]
public static bool AuthorizationRulesAreSuspended;
public SuspendedAuthorizationScope()
{
AuthorizationRulesAreSuspended = true;
}
public void Dispose()
{
AuthorizationRulesAreSuspended = false;
}
}
这是 IsAuthorized 检查(来自基类):
public bool IsAuthorized(string memberName, AuthorizedAction authorizationAction)
{
if (SuspendedAuthorizationScope.AuthorizationRulesAreSuspended)
return true;
var context = new RulesContext();
_rules.OfType<IAuthorizationRule>()
.Where(r => r.PropertyName == memberName)
.Where(r => r.AuthorizedAction == authorizationAction)
.ToList().ForEach(r => r.Execute(context));
return context.HasNoErrors();
}
这是演示用法的 ValidateProperty 方法(来自基类):
private void ValidateProperty(string propertyName, IEnumerable<IValidationRule> rules)
{
using (new SuspendedAuthorizationScope())
{
var context = new RulesContext();
rules.ToList().ForEach(rule => rule.Execute(context));
if (HasNoErrors(context))
RemoveErrorsForProperty(propertyName);
else
AddErrorsForProperty(propertyName, context.Results);
}
NotifyErrorsChanged(propertyName);
}
我对范围对象进行了一些测试,表明只要 lambda 在 using 语句的范围内解析,就会使用 SuspendedAuthorizationScope.AuthorizationRulesAreSuspended 的预期/正确值。
这个设计有什么明显的缺陷吗?就线程而言,我应该关注 ASP.NET 中的任何内容吗?