嗨,我正在使用FluentSecurity对MVC应用程序中的用户权限进行身份验证。在基本设置中,当用户想要访问被拒绝的Action
时,会引发异常。我想知道我应该如何重定向到另一个页面(如登录页面(,而不是显示黄色的异常页面?
我知道这个问题已经得到了回答,但我不喜欢在处理这种情况的每一个动作中都尝试捕捉。
Fluent Security允许您注册违反策略的处理程序(请参阅https://github.com/kristofferahl/FluentSecurity/wiki/Policy-violation-handlers)。您必须有一个从IPolicyViolationHandler继承的类。惯例是将您的类命名为<PolicyViolationName>PolicyViolationHandler
以下是注册拒绝匿名访问策略违反处理程序的处理程序示例
/// <summary>
/// Custom Policy Violation Handler. See http://www.fluentsecurity.net/wiki/Policy-violation-handlers
/// </summary>
public class DenyAnonymousAccessPolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
Flash.Error("You must first login to access that page");
return new RedirectResult("/");
}
}
您将遇到的另一个警告是,您必须使用IOC容器来注册这些处理程序。我不会争论使用IOC容器是好是坏,但如果我没有,我宁愿不使用。在他们的网站上,有一个博客写着如何在不使用国际奥委会集装箱的情况下做到这一点,但我也不太喜欢这种方法。以下是我所做的。
public static class SecurityConfig
{
public static void Configure()
{
SecurityConfigurator.Configure(c =>
{
c.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
c.GetRolesFrom(() => (HttpContext.Current.Session["Roles"] as string[]));
// Blanked Deny All
c.ForAllControllers().DenyAnonymousAccess();
// Publicly Accessible Areas
c.For<LoginController>().Ignore();
// This is the part for finding all of the classes that inherit
// from IPolicyViolationHandler so you don't have to use an IOC
// Container.
c.ResolveServicesUsing(type =>
{
if (type == typeof (IPolicyViolationHandler))
{
var types = Assembly
.GetAssembly(typeof(MvcApplication))
.GetTypes()
.Where(x => typeof(IPolicyViolationHandler).IsAssignableFrom(x)).ToList();
var handlers = types.Select(t => Activator.CreateInstance(t) as IPolicyViolationHandler).ToList();
return handlers;
}
return Enumerable.Empty<object>();
});
});
}
}
我从不使用FluentSecurity
,但您可以按照这种方式在操作中重定向。例如
public ActionResult YourActionName()
{
try
{
}
catch ( Exception )
{
return RedirectToAction("Index", "Home");
}
}
此外,您还可以使用控制器类上的HandleError
属性来捕获任何未处理的异常,它将自动返回Shared文件夹中的Error.aspx
视图。你也可以自定义它。
欲了解更多信息,请查看ScottGu的帖子。http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx
当前FluentSecurity稳定版本(1.4(没有任何内置功能来处理PolicyViolationException
,但您可以创建一个过滤器来实现这一点,比如:
public class PolicyViolationExceptionHandler : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception.GetType() == typeof(PolicyViolationException))
{
var routeDictionary = new RouteValueDictionary(new
{
area = "",
controller = "account",
action = "login"
});
// Redirect to specific page
filterContext.HttpContext.Response.RedirectToRoute(routeDictionary);
// Prevent to handle exceptions
// Of 'PolicyViolationException' by default filters
filterContext.ExceptionHandled = true;
}
}
}