我建議一個自定義Authorize
屬性(因爲你已經猜到了)。
這裏是下面一個例子:
public class BlackBoxAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool authorized = base.AuthorizeCore(httpContext);
if (authorized)
{
var routeData = httpContext.Request.RequestContext.RouteData;
var controller = routeData.GetRequiredString("controller");
var action = routeData.GetRequiredString("action");
bool canAccess = BlackBox.HasAccess(controller, action, userGuid);
if (!canAccess)
{
httpContext.Items["BlackBoxError"] = true;
return false;
}
return true;
}
else
{
return authorized;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
bool blackBoxError = filterContext.HttpContext.Items["BlackBoxError"] != null && Convert.ToBoolean(filterContext.HttpContext.Items["BlackBoxError"].ToString());
if (blackBoxError)
{
//change the controler name and action name accordingally as needed.
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "controller", "Error" },
{ "action", "BlackBoxError" }
}
);
}
base.HandleUnauthorizedRequest(filterContext);
}
}
有了這個地方你必須與BlackBoxAuthorizeAttribute
替換所有AuthorizeAttribute
註解。或者更好:從控制器中刪除AuthorizeAttribute
,並在app_start中註冊一個全局屬性。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new BlackBoxAuthorizeAttribute());
}
希望這會有所幫助!
問候, 烏羅什
如果BlackBox不是靜態的呢?這是緊密的耦合,這似乎有點問題... – Bartosz