gpt4 book ai didi

c# - 如何重定向到 FluentSecurity 中的特定页面?

转载 作者:行者123 更新时间:2023-11-30 16:20:37 25 4
gpt4 key购买 nike

您好,我正在使用 FluentSecurity在我的 MVC 应用程序中验证和验证用户权限。在基本设置中,当用户想要访问被拒绝的 Action 时,它会抛出异常。我想知道如何重定向到另一个页面(例如登录页面)而不是显示黄色异常页面?

最佳答案

我知道这个问题已经得到了回答,但我不喜欢在处理这种情况的每一个 Action 中都尝试捕捉。

Fluent Security 允许您为策略违规注册一个处理程序(参见 https://github.com/kristofferahl/FluentSecurity/wiki/Policy-violation-handlers)。您必须有一个继承自 IPolicyViolationHandler 的类。惯例是将您的类(class)命名为 <PolicyViolationName>PolicyViolationHandler

这是注册 DenyAnonymousAccessPolicyViolationHandler 的处理程序示例

    /// <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 容器是好是坏,但如果我没有的话,我宁愿不使用。在他们的网站上,有一篇博客介绍了如何在不使用 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>();
});
});
}
}

关于c# - 如何重定向到 FluentSecurity 中的特定页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14019985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com