嘿,我已经succesfull能够在我的FilterAttribute中使用属性注入,但我想知道是否有可能将其移入构造函数呢?ASP.NET MVC3 + ActionFilterAttribute + Injection?
我当前的代码:
// 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
}
在此先感谢!
TheCloudlessSky是正确的,当你只使用一个属性。过滤器可以使用构造函数注入,但是你需要将一个属性绑定到过滤器上......我在下面提供了一个答案;感谢Remo Gloor,B Z和其他人的帮助。 –