MVC中使用AuthorizeAttribute做身份验证操作
代码顺序为:OnAuthorization-->AuthorizeCore-->HandleUnauthorizedRequest
假设AuthorizeCore返回false时,才会走HandleUnauthorizedRequest 方法,而且Request.StausCode会返回401,401错误又相应了Web.config中
的
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
全部,AuthorizeCore==false 时,会跳转到 web.config 中定义的 loginUrl="~/"
public class CheckLoginAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext) {
bool Pass = false;
if (!CheckLogin.AdminLoginCheck())
{
httpContext.Response.StatusCode = 401;//无权限状态码
Pass = false;
}
else
{
Pass = true;
}
return Pass;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if(filterContext.HttpContext.Request.IsAjaxRequest())
{
if (!App.AppService.IsLogon)
{
filterContext.Result = new JsonResult
{
Data = new {IsSuccess = false, Message = "不好意思,登录超时,请又一次登录再操作!"},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return;
}
}
if (App.AppService.IsLogon)
{
return;
}
base.HandleUnauthorizedRequest(filterContext);
if (filterContext.HttpContext.Response.StatusCode == 401)
{
filterContext.Result = new RedirectResult("/");
}
}
}
AuthorizeAttribute的OnAuthorization方法内部调用了AuthorizeCore方法,这种方法是实现验证和授权逻辑的地方,假设这种方法返回true,
表示授权成功,假设返回false, 表示授权失败, 会给上下文设置一个HttpUnauthorizedResult,这个ActionResult运行的结果是向浏览器返回
一个401状态码(未授权),可是返回状态码没什么意思,一般是跳转到一个登录页面,能够重写AuthorizeAttribute的
HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context == null)
{
throw new ArgumentNullException("filterContext");
}
else
{
string path = context.HttpContext.Request.Path;
string strUrl = "/Account/LogOn?returnUrl={0}";
context.HttpContext.Response.Redirect(string.Format(strUrl, HttpUtility.UrlEncode(path)), true);
}
}
相关文章
- MVC Html.AntiForgeryToken() 防止CSRF攻击
- TransactionScope事务处理方法介绍及.NET Core中的注意事项 SQL Server数据库漏洞评估了解一下 预热ASP.NET MVC 的VIEW [AUTOMAPPER]反射自动注册AUTOMAPPER PROFILE
- C# -- 等待异步操作执行完成的方式 C# -- 使用委托 delegate 执行异步操作 JavaScript -- 原型:prototype的使用 DBHelper类连接数据库 MVC View中获取action、controller、area名称、参数
- EF+LINQ事物处理 C# 使用NLog记录日志入门操作 ASP.NET MVC多语言 仿微软网站效果(转) 详解C#特性和反射(一) c# API接受图片文件以Base64格式上传图片 .NET读取json数据并绑定到对象
- ASP.NET MVC下实现前端视图页的Session
- 在ASP.NET MVC中使用Knockout实践05,基本验证
- MVC三级联动无刷新
- datagrid在MVC中的运用04-同时添加搜索和操作区域
- datagrid在MVC中的运用01-基本属性并实现分页
- Android 应用架构指南 -- 三种架构模式简介(MVC、MVP、MVVM)
- Asp.Net Core MVC 中富文本编辑器CKEditor 5的配置及使用
- MVC中使用AuthorizeAttribute做身份验证操作【转】
- MVC中使用AuthorizeAttribute做身份验证操作
- Injecting and Binding Objects to Spring MVC Controllers--转
- ASP.NET MVC+BUI实现表格的操作