且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC 授权

更新时间:2023-02-14 16:37:40

使用 Authorize 属性

Use the Authorize attribute

[Authorize]
public ActionResult MyAction()
{
   //stuff
}

您也可以在控制器上使用它.也可以传入用户或角色.

You can also use this on the controller. Can pass in users or roles too.

如果你想要更多控制的东西,你可以尝试像这个.

If you want something with a little more control, you could try something like this.

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string[] users = Users.Split(',');

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            if (users.Length > 0 &&
                !users.Contains(httpContext.User.Identity.Name,
                    StringComparer.OrdinalIgnoreCase))
                return false;

            return true;
        }
    }