Вы можете найти от AuthorizeAttribute
и обрабатывать его так, как хотите. Запрос сначала ударит этот переопределенный метод, чтобы дать вам возможность решить, разрешить ли запрос обслуживаться дальше или отклонить его. Вы также можете проигнорировать какой-либо конкретный метод, например Login, добавив атрибут AllowAnonymous
или определите свой собственный атрибут, исходя из класса Attribute
.
рабочий пример ниже:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RdbiAuthorizationAttribute : AuthorizeAttribute
{
/// <summary>
/// Verifies that the logged in user is a valid organization user.
/// </summary>
/// <param name="filterContext"></param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
Guard.ArgumentNotNull(filterContext, "filterContext");
Guard.ArgumentNotNull(filterContext.Controller, "filterContext.Controller");
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(
typeof(AllowAnonymousAttribute), inherit: true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
typeof(AllowAnonymousAttribute), inherit: true);
if (skipAuthorization)
{
return;
}
if (string.IsNullOrEmpty(filterContext.HttpContext.User.Identity.Name))
throw new AuthenticationException("User must be logged in to access this page.");
var controller = filterContext.Controller as BaseController;
if (controller != null)
{
var user = controller.GetUser();
if (user == null)
{
throw new InvalidOperationException(string.Format("Logged in user {0} is not a valid user", filterContext.HttpContext.User.Identity.Name));
}
}
base.OnAuthorization(filterContext);
}
}
Если я правильно код вы предоставили, filterContext.Controller уже содержит экземпляр контроллера. Поэтому, что бы я ни писал внутри OnAuthorization, это не изменит тот факт, что контроллер уже создан. – SiberianGuy
Я не понимаю, почему вас беспокоит, создан ли экземпляр контроллера или нет. Если вы обрабатываете запрос, вы можете вернуть соответствующий ответ (401) пользователю, и он не получит доступ к какому-либо ресурсу, на который у него нет прав. Я пропустил ваше требование? – SBirthare