我目前正在使用以下代码进行拦截(非常简单):
(见底部问题)
我的拦截器:
public interface IAuthorizationInterceptor : IInterceptor { }
public class AuthorizationInterceptor : IAuthorizationInterceptor
{
public IParameter[] AttributeParameters { get; private set; }
// This doesnt work currently... paramters has no values
public AuthorizationInterceptor(IParameter[] parameters) {
AttributeParameters = parameters;
}
public void Intercept(IInvocation invocation) {
// I have also tried to get the attributes like this
// which also returns nothing.
var attr = invocation.Request.Method.GetCustomAttributes(true);
try {
BeforeInvoke(invocation);
} catch (AccessViolationException ex) {
} catch (Exception ex) {
throw;
}
// Continue method and/or processing additional attributes
invocation.Proceed();
AfterInvoke(invocation);
}
protected void BeforeInvoke(IInvocation invocation) {
// Enumerate parameters of method call
foreach (var arg in invocation.Request.Arguments) {
// Just a test to see if I can get arguments
}
//TODO: Replace with call to auth system code.
bool isAuthorized = true;
if (isAuthorized == true) {
// Do stuff
}
else {
throw new AccessViolationException("Failed");
}
}
protected void AfterInvoke(IInvocation invocation) {
}
}
我的属性:
public class AuthorizeAttribute : InterceptAttribute
{
public string[] AttributeParameters { get; private set; }
public AuthorizeAttribute(params string[] parameters) {
AttributeParameters = parameters;
}
public override IInterceptor CreateInterceptor(IProxyRequest request) {
var param = new List<Parameter>();
foreach(string p in AttributeParameters) {
param.Add( new Parameter(p, p, false));
}
// Here I have tried passing ConstructorArgument(s) but the result
// in the inteceptor constructor is the same.
return request.Context.Kernel.Get<IAuthorizationInterceptor>(param.ToArray());
}
}
应用于一种方法:
[Authorize("test")]
public virtual Result<Vault> Vault(DateTime date, bool LiveMode = true, int? SnapshotId = null)
{
...
}
这是有效的,我可以通过属性传递额外的参数,如下所示:
[Authorize("test")]
如果你注意到在我的属性中,我正在从属性中获取一些参数,我可以在属性类中访问这些参数,但我无法将这些参数传递给拦截器。我已尝试在内核中使用ConstructorArgument。Get<>()调用,它不会抛出错误,但AuthorizationInterceptor构造函数不会从ninject中获取任何值。正如您在代码示例中看到的,我也尝试过GetCustomAttributes(),但它也没有返回任何结果。从其他类似的帖子来看(NinjectInterception3.0Interface方法代理属性),这似乎是正确的方法,但它不起作用。有什么想法吗?
我能够通过在拦截器上创建一个初始化方法来完成一些工作。我真的不喜欢它,因为它将我与AuthorizationInterceptor的具体实现联系在一起,但它完成了任务(该死的截止日期,哈哈)。我仍然想知道是否有更好的方法来做到这一点,所以我不会标记我自己的答案,希望有人能想出更好的方法。
我修改属性如下:
public override IInterceptor CreateInterceptor(IProxyRequest request) {
AuthorizationInterceptor attr = (AuthorizationInterceptor)request.Context.Kernel.Get<IAuthorizationInterceptor>();
attr.Init(AttributeParameters);
return attr;
}
并在拦截器上创建了一个Init方法:
public void Init(params string[] parameters) {
AttributeParameters = parameters;
}