Ninject атрибут перехвата с параметрами, переданными перехватчику?
У меня есть перехват, работающий в настоящее время (очень упрощенно) со следующим кодом:
(см. вопрос внизу)
Мой перехватчик:
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 в вызове Kernel.Get<>(), который не выдает ошибку, но конструктор AuthorizationInterceptor не получает никаких значений из ninject. Я также пробовал GetCustomAttributes(), как вы можете видеть в примере кода, но это также ничего не возвращает. Если посмотреть на другие подобные посты, такие как ( интерфейсный прокси-сервер Ninject Interception 3.0 по атрибутам методов), то это правильный путь, но он не работает. Есть идеи?
1 ответ
Я смог заставить что-то работать, создав метод инициализации на перехватчике. Мне это не очень нравится, потому что оно связывает меня с конкретной реализацией 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;
}