如果未设置特定角色/声明,请使用应用于控制器的过滤器:
public class CheckAuthorizationFilter : ActionFilterAttribute
{
private static readonly List<string> Exceptions = new List<string>
{
"account/",
"public/"
};
/// <summary>
/// Called by the ASP.NET MVC framework before the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuting([NotNull] ActionExecutingContext filterContext)
{
Contract.Requires(filterContext != null);
Contract.Requires(filterContext.HttpContext != null);
Contract.Requires(filterContext.HttpContext.User != null);
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
string actionName =
$"{filterContext.ActionDescriptor.ControllerDescriptor.ControllerName}/{filterContext.ActionDescriptor.ActionName}"
.ToLower();
if (!Exceptions.Any(actionName.StartsWith))
{
UserProfile user = UserProfileCache.Instance.Get(new TimeJackContext(),
new object[] {filterContext.HttpContext.User.Identity.GetUserId()});
if (user == null || user.UserState != UserState.Active)
{
SessionMessage.AddMessage(
$"You ({filterContext.HttpContext.User.Identity.Name}) are not allowed to use this smart tool at this time.", SessionMessage.MessageType.warning);
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{"Controller", "Account"},
{"Action", "LogOff"}
});
}
}
}
base.OnActionExecuting(filterContext);
}
}
并将过滤器添加到全局过滤器列表中:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
Contract.Requires(filters != null);
filters.Add(new DatabaseUpgradeNeededFilter());
filters.Add(new HandleErrorAttribute());
filters.Add(new WarnAboutOldBrowsersAttribute());
filters.Add(new CheckAuthorizationFilter()); // <---
filters.Add(new RedirectToSslFilter());
// ...
}