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