在MVC中定义自己的权限特性。

下例中是简单的登录判断,登录信息存与Session中,如果Session中没有登录信息,那么就不通过。

在处理无权限的时候,判断当前请求是否为Ajax请求,如果是Ajax请求,返回Json {state=-1,msg="请登录"},如过不是Ajax请求那么就直接重定向到登录页面。

/// <summary>
/// 授权特性
/// </summary>
public class MyAuthorizeAttribute : AuthorizeAttribute
{
string errcode = null; /// <summary>
/// 授权核心
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var loginInfo = httpContext.Session["login"];
if (loginInfo == null)
{
errcode = "NotLoggedIn";
return false;
}
// 登录用户信息
UserIdentity userIdentity = new UserIdentity((AdminInfo)loginInfo);
httpContext.User = new UserPrincipal(userIdentity); return true;
} /// <summary>
/// 处理无权限请求
/// </summary>
/// <param name="filterContext"></param>
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// 没有登录
if (errcode == "NotLoggedIn")
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
filterContext.Result = new JsonResult
{
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { state = -, msg = "请重新登录" },
};
}
else
{
filterContext.Result = new RedirectResult("/Account/Login");
}
}
return;
}
}

最新文章

  1. php实现中文转数字,实现方式很智能很php
  2. ActiveMQ笔记(3):基于Networks of Brokers的HA方案
  3. android 真机调试出现错误 INSTALL_FAILED_INSUFFICIENT_STORAGE 的解决方法。
  4. 开源一个完整的iOSApp《丁丁美图》供初学者学习
  5. Please allow Subclipse team to receive anonymous usage statistics for this Eclipse intance(info)
  6. python核心编程学习记录之函数与函数式编程
  7. HTTP2 学习
  8. Linux Socket过程详细解释(包括三次握手建立连接,四次握手断开连接)
  9. [ionic开源项目教程] - 第2讲 新建项目,配置app.js和controllers.js搭建基础视图
  10. 【原创】leetCodeOj ---Convert Sorted List to Binary Search Tree 解题报告
  11. unity3d教程-01-安装及使用Unity
  12. Java基础语法&lt;三&gt; 输入输出
  13. [技术] OIer的STL入门教程
  14. 转:python request属性及方法说明
  15. utils工具类
  16. .NET页面导出Excel
  17. sqlserver 添加服务器链接 跨服务器访问数据库
  18. SQLServer转MYSQL的方法(连数据)[传]
  19. SparkSQL UDF两种注册方式:udf() 和 register()
  20. BCB ERROR:[Linker Error] &#39;XXX.LIB&#39; contains invalid OMF record, type 0x21 (possibly COFF)

热门文章

  1. node使用art-template的过滤器
  2. 16、ISDN
  3. Java数据类型及对应取值范围
  4. Linux基础与搭建
  5. go接口详解
  6. 记一个实时Linux的中断线程化问题
  7. Nginx 部署及配置
  8. 【算法】混合流体模拟demo
  9. 详解Java8的日期和时间API
  10. bat常用符合和for语句等