4 回答

TA貢獻(xiàn)1836條經(jīng)驗 獲得超3個贊
如果要使用構(gòu)造函數(shù)注入,則需要創(chuàng)建一個屬性和一個過濾器。
///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貢獻(xiàn)1815條經(jīng)驗 獲得超10個贊
我為Ninject無法處理構(gòu)造的任何情況找到了一個簡單的解決方案:
var session = (IMyUserService)DependencyResolver.Current.GetService(typeof (IMyUserService));
實際上,這正是我與自定義AuthorizeAttribute一起使用的內(nèi)容。比必須實現(xiàn)單獨的FilterAttribute容易得多。
- 4 回答
- 0 關(guān)注
- 587 瀏覽
添加回答
舉報