c# - 在 MVC3 中未授权页面时重定向用户

标签 c# asp.net-mvc asp.net-mvc-3 error-handling active-directory

我有一个mvc 3 项目,我使用AD 来授权用户。 我有一个页面,只有具有“管理员”角色的用户才能访问。

我已经让登录生效并授权用户,这样只有管理员才能访问网站的管理部分。 我遇到的问题是当用户不是管理员时,我似乎无法显示正确的错误消息。

这是我的 actionFilterattribute

public class AdminOnlyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        bool isAuthorised = false;

        IPrincipal user = filterContext.HttpContext.User;
        if (user.Identity.IsAuthenticated)
        {
            if (user.IsInRole("Admin"))
            {
                isAuthorised = true;
            }
        }

        if (!isAuthorised)
        {
            //error message here
        }
    }

这是我的管理员 Controller

    [AdminOnly]
        public ActionResult Index()
        {
        //admin stuff
        }

感谢任何帮助,提前致谢

最佳答案

如果 isAuthorised 为假,您需要将他们带到一个可以显示“您无权访问该页面等”的页面。要进行重定向,您必须执行以下操作(在我的示例中,我将它们重定向到 Account/AccessDenied,这将返回一个包含“您没有访问权限等...”消息的 View :

if (!isAuthorised)
{
    filterContext.Result = new RedirectToRouteResult(
        new RouteValueDictionary {{"action", "AccessDenied"}, 
            {"controller", "Account"}});
}

关于c# - 在 MVC3 中未授权页面时重定向用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10483036/

相关文章:

c# - 在 asp.net 中重新加载页面期间 Cookie 被清除

c# - Mono 中的 HTTP 监听器不读取 HTTP 请求

c# - 如何在 ASP.NET Core 的 Startup.cs 中注册 RoleManager

asp.net-mvc - 在 MVC 4 中的另一个表单中验证 JQuery UI 模式表单

asp.net - Web 部署任务失败

c# - 使用 ProcessStartInfo 为 UAC 重定向标准输出和提示

c# - 通知 ajax 调用 session 已超时或用户需要重新验证

javascript - 单击链接调用 javascript 函数

asp.net-mvc-3 - 如何对部分 View 进行批量持久化?

javascript - 如何用 Jquery/JS 交换 2 @Html.DropDownListFor