1、新建类BaseController用于统一所有控制器继承扩展,方便扩展登录等过滤器。示例如下:

using CloudWave.JustBeHere.JBH_H5.Controllers.Attribute;
using CloudWave.JustBeHere.JBH_H5.Controllers.Authorization;
using CloudWave.JustBeHere.JBH_H5.Models.User;
using CloudWave.JustBeHere.Web;
using Jil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using static CloudWave.JustBeHere.JBH_H5.Models.Commn.BaseModel;namespace CloudWave.JustBeHere.JBH_H5.Controllers
{[Auth][ResultFilter]
#if (!DEBUG)[Error]
#endifpublic class BaseController : Controller{public Authentication authentication = Authentication.Instance;public bool IsLogin{get{//return true;return authentication.IsLogin;}}public LoginResult Operator{get{return authentication.CurrentUser;}}private string _hostName;/// <summary>/// 获取请求的域名/// </summary>public string HostName{get{if (string.IsNullOrEmpty(_hostName)){var url = Request.Url.ToString();// http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]?var reg = new Regex(@"//([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]+/?");var result = reg.Match(url, 0).Value;_hostName = result;}return _hostName;}}private string _hostFullName;/// <summary>/// 获取请求的域名全称(含请求协议)/// </summary>public string HostFullName{get{if (string.IsNullOrEmpty(_hostFullName)){var url = Request.Url.ToString();// http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]?var reg = new Regex(@"http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]+/?");var result = reg.Match(url, 0).Value;_hostFullName = result;}return _hostFullName;}}/// <summary>/// 是否为手机端访问/// </summary>public bool IsMobile{get{var uAgent = Request.ServerVariables["HTTP_USER_AGENT"];var b = new Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);var v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);return b.IsMatch(uAgent) || v.IsMatch(uAgent.Substring(0, 4));}}}
}

View Code

2、新建类Authentication用于管理SessionCookie等信息。示例如下:

using CloudWave.JustBeHere.JBH_H5.Models.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;namespace CloudWave.JustBeHere.JBH_H5.Controllers.Authorization
{public class Authentication{public const string UserSessionKey = "UserInfo";private Authentication(){}public static Authentication Instance{get{return new Authentication();}}/// <summary>/// 写入验证信息/// </summary>/// <param name="uInfo"></param>/// <param name="isPersistent">是否保存</param>public void SetAuth(LoginResult uInfo, bool isPersistent){string token = uInfo.Id + "|" + uInfo.Token;//将用户ID和角色写入Cookie
            FormsAuthentication.SetAuthCookie(token, isPersistent, FormsAuthentication.FormsCookiePath);HttpCookie authCookie = FormsAuthentication.GetAuthCookie(token, isPersistent);FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);//FormsAuthentication.RedirectFromLoginPage(ticket.Name, true);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, DateTime.Now.AddDays(30), ticket.IsPersistent, "");authCookie.Value = FormsAuthentication.Encrypt(newTicket);HttpContext.Current.Response.AddHeader("P3P", "CP=CAO PSA OUR");//解决ie js跨域调用
            HttpContext.Current.Response.Cookies.Add(authCookie);SetSession(uInfo);}/// <summary>///保存用户状态/// </summary>/// <param name="uInfo"></param>public void SetSession(LoginResult uInfo){HttpContext.Current.Session[UserSessionKey] = uInfo;}/// <summary>///保存用户状态/// </summary>/// <param name="uid"></param>public void SetSession(int uid){bool setFlag = false;if (HttpContext.Current.Session == null){throw new ArgumentNullException("SessionState Failed");}if (HttpContext.Current.Session[UserSessionKey] == null){setFlag = true;}else{//得到用户信息LoginResult sulr = HttpContext.Current.Session[UserSessionKey] as LoginResult;if (sulr.Id != uid) setFlag = true;}if (setFlag){try{//var u = GetUserInfo();//if (u != null)//{//    HttpContext.Current.Session[UserSessionKey] = u;//}new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "Index", controller = "Home" }));}catch { }}}private LoginResult GetUserInfo(){var client = new Api(WebCommon.ApiUrl, WebCommon.ActiveUser, WebCommon.ApiToken);LoginResult slr = new LoginResult();client.Request.Header.Cmd = "api/staffuser/getstaffuserinfo";slr = client.ExecutePost<LoginResult>();if (client.Response.Header.statusCode == 1000){return slr;}else { return null; }}/// <summary>/// 登出/// </summary>public void SignOut(){FormsAuthentication.SignOut();HttpContext.Current.Session.Clear();}public bool IsLogin{get{return HttpContext.Current != null ? HttpContext.Current.Request.IsAuthenticated : false;}}/// <summary>/// 当前用户信息/// </summary>public LoginResult CurrentUser{get{if (!IsLogin){return null;}int uid;if (int.TryParse(HttpContext.Current.User.Identity.Name.Split('|')[0], out uid)){if (HttpContext.Current.Session[UserSessionKey] == null){SetSession(uid);}return HttpContext.Current.Session[UserSessionKey] as LoginResult;}return null;}}//public void RefreshInfo()//{//    UsersExtensionInfo u = UsersService.GetById(HttpContext.Current.User.Identity.Name);//    u.ImName = UsersService.GetImName(u.TTUserId);//    HttpContext.Current.Session[UserSessionKey] = UserInfoDec(u);//}
    }
}

View Code

3、新建类AuthAttribute,继承AuthorizeAttribute类。示例如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;namespace CloudWave.JustBeHere.JBH_H5.Controllers.Attribute
{/// <summary>/// 登录过滤器/// </summary>public class AuthAttribute : AuthorizeAttribute{public override void OnAuthorization(AuthorizationContext filterContext){var controller = filterContext.Controller as BaseController;if (controller.IsLogin){filterContext.Controller.ViewBag.UserInfo = controller.Operator?.Id;// filterContext.Controller.ViewBag.PartnerName = controller.Operator?.PartnerName;
            }else{filterContext.Controller.ViewBag.UserInfo = "";//  filterContext.Controller.ViewBag.PartnerName = "";
            }if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)){if (!controller.IsLogin){//if (filterContext.HttpContext.Request.IsAjaxRequest())//{//    filterContext.Result = new JsonResult//    {//        Data = "needlogin",//        JsonRequestBehavior = JsonRequestBehavior.AllowGet//    };//}//else//{//    string reutrnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;//    filterContext.Result = new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "index", controller = "Home", returnUrl = reutrnUrl }));//}string reutrnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;filterContext.Result = new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "index", controller = "Home", returnUrl = reutrnUrl }));}}//if (!AuthorizeCore(filterContext.HttpContext)) {//    HandleUnauthorizedRequest(filterContext);//} else {//    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);//}
        }}
}

View Code

4、在Web.config的节点system.web下新增如下节点配置:

<authentication mode="Forms"><forms loginUrl="/Home/Index" timeout="43200"></forms>
</authentication>

5、返回信息过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;namespace CloudWave.JustBeHere.JBH_H5.Controllers.Attribute
{/// <summary>/// 请求返回结果过滤器/// </summary>public class ResultFilterAttribute : ActionFilterAttribute{public override void OnResultExecuting(ResultExecutingContext filterContext){if (filterContext.Result is ViewResult){var controller = (BaseController)filterContext.Controller;FormsAuthentication.SignOut();HttpContext.Current.Session.Clear();}base.OnResultExecuting(filterContext);}}
}

View Code

转载于:https://www.cnblogs.com/miskis/p/8716263.html

Asp.Net MVC 自定义登录过滤器相关推荐

  1. asp.net mvc 自定义全局过滤器 验证用户是否登录

    一般具有用户模块的系统都需要对用户是否登录进行验证,如果用户登录了就可以继续操作,否则退回用户的登录页面 对于这样的需求我们可以通过自定义一个独立的方法来完成验证的操作,但是这样代码的重复率就大大提高 ...

  2. ASP.NET MVC使用Authorize过滤器验证用户登录

    ASP.NET MVC使用Authorize过滤器验证用户登录.Authorize过滤器首先运行在任何其它过滤器或动作方法之前,主要用来做登录验证或者权限验证. 示例:使用Authorize过滤器实现 ...

  3. ASP.NET MVC 自定义Razor视图WorkContext

    概述 1.在ASP.NET MVC项目开发的过程中,我们经常需要在cshtml的视图层输出一些公用信息 比如:页面Title.服务器日期时间.页面关键字.关键字描述.系统版本号.资源版本号等 2.普通 ...

  4. ASP.NET MVC 自定义路由中几个需要注意的小细节

    本文主要记录在ASP.NET MVC自定义路由时,一个需要注意的参数设置小细节. 举例来说,就是在访问 http://localhost/Home/About/arg1/arg2/arg3 这样的自定 ...

  5. asp.net mvc 自定义 pager 封装与优化

    asp.net mvc 自定义 pager 封装与优化 Intro 之前做了一个通用的分页组件,但是有些不足,从翻页事件和分页样式都融合在后台代码中,到翻页事件可以自定义,再到翻页和样式都和代码分离, ...

  6. [Asp.net MVC]HandleErrorAttribute异常过滤器

    [Asp.net MVC]HandleErrorAttribute异常过滤器 参考文章: (1)[Asp.net MVC]HandleErrorAttribute异常过滤器 (2)https://ww ...

  7. ASP.NET MVC自定义AuthorizeAttribute篇知识点讲解—登录限制

    阅读目录 1.前言 2.AuthorizeAttribute登录特性解释 3.代码示例 1.前言 a.微软对ASP.NET的开发从WebForm到MVC的转变,已经正式过去5,6个年头,现在WebFo ...

  8. ASP.net MVC自定义错误处理页面的方法

    在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...

  9. ASP.NET MVC 4 (三) 过滤器

    先来看看一个例子演示过滤器有什么用: public class AdminController : Controller { // ... instance variables and constru ...

最新文章

  1. js阿拉伯数字转成汉字
  2. 华为linux笔记本开售,华为 MateBook D Linux 版明天开售 一种价格两种版本
  3. 屏幕滚动控件ScrollView的使用
  4. Spring Remoting: Hessian--转
  5. C语言,期末复习之穷举法鸡兔同笼问题
  6. kail linux更新源、挂载
  7. 计算机导航医学应用,计算机导航技术在口腔颌面外科应用中的新发展
  8. 递归算法和经典递归例子
  9. 微信小程序云开发之初体验(详细教程)
  10. BP算法推导-softmax层+交叉熵(logloss)
  11. php使用手册输出语句,php echo和print区别及语句用法是什么 - php完全自学手册 - php中文网手册...
  12. python使用selenium模拟浏览器进入好友QQ空间留言
  13. C++游戏---皇后PK
  14. Android Bmob后端云—数据库、服务器!
  15. Python 提示 ModuleNotFoundError: No module named ‘common‘
  16. 语言大数据起航,大数据量级加码
  17. 音频 ----- DRC
  18. SpringBoot并发压测工具ContiPerf
  19. VS2019 配色_NBA球员上脚:基德穿AJ13湖人配色,莫兰特的保罗乔治4代
  20. selenium之DDT:使用DDT模块实现数据驱动测试

热门文章

  1. Jquery+CSS Input file 文本框轻美化
  2. mysql 多条记录判断相加减进行计算
  3. 太原警方通过微博提醒您手机丢失如何保微信安全
  4. 轻松实现SQL Server与Access、Excel数据表间的导入导出
  5. Flutter Text详解
  6. 广度优先算法_算法浅谈——走迷宫问题与广度优先搜索
  7. python time模块计时_python中计时模块timeit的使用方法
  8. ASP.NET 是什么
  9. 空调开28度,一晚上会消耗多少电?空调耗电量与什么有关?
  10. 创业者都有一个共同的特质,他想做事,就立刻做