如何在ASP中实现允许匿名访问者,但不允许登录用户的操作方法.asp.net MVC 5

本文关键字:用户 登录 不允许 操作方法 asp MVC net ASP 实现 访问者 许匿名 | 更新日期: 2023-09-27 18:03:44

请展示一下c# mvc5中允许匿名访问而不允许登录用户使用操作方法的可能性。

在我的例子中,我不能只允许一些特定的用户作为他们的角色

ex Admin角色的用户不允许

,

允许使用Worker角色的用户

如何在ASP中实现允许匿名访问者,但不允许登录用户的操作方法.asp.net MVC 5

我终于得到了正确的解

public class AllowAnonymousOnlyAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool userId = HttpContext.Current.User.Identity.IsAuthenticated;
            if (userId)
            {
                if (HttpContext.Current.User.IsInRole("Admin") || HttpContext.Current.User.IsInRole("Doctor"))
                {
                    filterContext.HttpContext.Response.Redirect("/Home/Index");
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }