Hey there, I've succesfull been able to use property injection in my FilterAttribute, however I'm wondering whether its possible to move it into the constructor instead?
My current code:
// AuthAttribute.cs
public class AuthAttribute : ActionFilterAttribute
{
public Roles _authRoles { get; private set; }
[Inject]
private readonly IAuthorizationService _service;
public AuthAttribute(Roles roles)
{
_authRoles = roles;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
string redirectUrl = string.Format("?returnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
else
{
bool isAuthorized = _service.Authorize(GetUserSession.Id, _authRoles.ToString());
if (!isAuthorized)
{
// TODO: Make custom "Not Authorized" error page.
throw new UnauthorizedAccessException("No access");
}
}
}
}
// TestController.cs
[Auth(Roles.Developer)]
public ActionResult Index()
{
// Some smart logic
}
Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…