4 回答
TA贡献1836条经验 获得超3个赞
如果要使用构造函数注入,则需要创建一个属性和一个过滤器。
///marker attribute
public class MyAuthorizeAttribute : FilterAttribute { }
//filter
public class MyAuthorizeFilter : IAuthorizationFilter
{
private readonly IUserService _userService;
public MyAuthorizeFilter(IUserService userService)
{
_userService = userService;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var validUser = _userService.CheckIsValid();
if (!validUser)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "AccessDenied" }, { "controller", "Error" } });
}
}
}
捆绑:
this.BindFilter<MyAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenControllerHas<MyAuthorizeAttribute>();
控制器:
[MyAuthorizeAttribute]
public class YourController : Controller
{
}
嗯...
TA贡献1815条经验 获得超10个赞
我为Ninject无法处理构造的任何情况找到了一个简单的解决方案:
var session = (IMyUserService)DependencyResolver.Current.GetService(typeof (IMyUserService));
实际上,这正是我与自定义AuthorizeAttribute一起使用的内容。比必须实现单独的FilterAttribute容易得多。
- 4 回答
- 0 关注
- 541 浏览
添加回答
举报