asp.net-mvc-3 – 如何在MVC3上使用authorize属性

我已经读过要在MVC上使用属性[Authorize],你只需将它放在一个动作或你要保护的控制器类上.

我的问题是:Authorize属性如何知道用户是否已登录?我是否必须提供任何Session对象才能让Authorize知道用户是否获得授权?

解决方法

属性通过查看HttpContext.User.Identity.IsAuthenticated来工作.

如果您使用的是FormsAuthentication,如果用户的计算机上有一个有效的FormsAuthentication cookie(您可以使用FormsAuthentication.SetAuthCookie添加),则会将其设置为true.

如果您对Authorize的内部工作感兴趣,这来自已发布的Microsoft源代码

protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        } 

        IPrincipal user = httpContext.User; 
        if (!user.Identity.IsAuthenticated) { 
            return false;
        } 

        if (_useRSSplit.Length > 0 && !_useRSSplit.Contains(user.Identity.Name,StringComparer.OrdinalIgnoreCase)) {
            return false;
        } 

        if (_rolessplit.Length > 0 && !_rolessplit.Any(user.IsInRole)) { 
            return false; 
        }

        return true;
    }

这是some more info on FormsAuthentication.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....