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]
#endif
public 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, ).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, ).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(, ));
}
}
}
}

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(), 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 == )
{
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('|')[], 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);
//}
}
}

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);
//}
}
}
}

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);
}
}
}

Asp.Net MVC 自定义登录过滤器的更多相关文章

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

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

  2. ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)

    前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...

  3. Asp.Net MVC<五>:过滤器

    ControllerActionInvoker在执行过程中除了利用ActionDescriptor完成对目标Action方法本身的执行外,还会执行相关过滤器(Filter).过滤器采用AOP的设计,它 ...

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

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

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

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

  6. ASP.NET MVC学习之过滤器篇(2)

    下面我们继续之前的ASP.NET MVC学习之过滤器篇(1)进行学习. 3.动作过滤器 顾名思义,这个过滤器就是在动作方法调用前与调用后响应的.我们可以在调用前更改实际调用的动作,也可以在动作调用完成 ...

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

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

  8. Asp.net Mvc 自定义Session (二)

    在 Asp.net Mvc 自定义Session (一)中我们把数据缓存工具类写好了,今天在我们在这篇把 剩下的自定义Session写完 首先还请大家跟着我的思路一步步的来实现,既然我们要自定义Ses ...

  9. Asp.net mvc 自定义全局的错误事件HandleErrorAttribute无效

    Asp.net mvc 自定义全局的错误事件HandleErrorAttribute,结果无效, 原因: 1.没有在RegisterGlobalFilters 里面添加或者你要的位置添加. 2.你把这 ...

随机推荐

  1. 互评Alpha版本——基于NABCD评论作品,及改进建议

    组名:可以低头,但没必要 组长:付佳 组员:张俊余  李文涛  孙赛佳  田良  于洋  刘欣  段晓睿 一.杨老师粉丝群--<弹球学成语> 1.1 NABCD分析   N(Need,需求 ...

  2. 互评Alpha版本 - Hello World团队项目空天猎

    在测评该项目时,我找到了Hello World!团队的git,并下载了相关文件以及阅读了程序运行说明. 如图所示,我下载了一个名为 SkyHunter1.0.rar 的压缩文件包,文件包内容如下: 根 ...

  3. 《我是一只IT小小鸟》 读书笔记

    <我是一只IT小小鸟>讲述了IT人员的成长经历,邀请了许多名IT行业的职员,学生,研究生写了自己的亲身经历和人生感悟,以书中可以看到我国IT行业的快速进步,以及看到IT员在这条道路上的坎坷 ...

  4. PAT 甲级 1083 List Grades

    https://pintia.cn/problem-sets/994805342720868352/problems/994805383929905152 Given a list of N stud ...

  5. Ribbon源码解析

    SpringCloud中的Ribbon开源项目,提供了客户端的负载均衡算法.这篇文章,我们来介绍下他是如何实现的.为了方便理解,我们以客户端调用的流程来介绍,其中会穿插介绍相关源代码. 简单回顾下Ri ...

  6. Linux下修改环境变量PATH

    1.什么是环境变量(PATH) 在Linux中,在执行命令时,系统会按照PATH的设置,去每个PATH定义的路径下搜索执行文件,先搜索到的文件先执行. 我们知道查阅文件属性的指令ls 完整文件名为:/ ...

  7. 第201天:js---实现继承的5种方式

    一.构造函数方式 //构造函数 function People(){ this.race = '汉族'; } People.prototype={ eat:function(){ console.lo ...

  8. jquery不能是使用普通的for循环 因为普通的for循环通过下表获取对象 如果通过下表获取对象的话 会转成dom对象

    jquery不能是使用普通的for循环 因为普通的for循环通过下表获取对象 如果通过下表获取对象的话 会转成dom对象

  9. BZOJ 1212 L语言(DP+字典树)

    求能被理解的最长前缀. 很显然的dp.令dp[i]=true,表示前缀i能理解.否则不能理解.那么dp[i+len]=dp[i]=true,当s[len]能匹配str[i,i+len]. 由于模式串长 ...

  10. BZOJ 1066:[SCOI2007]蜥蜴(最大流)

    蜥蜴Description在一个r行c列的网格地图中有一些高度不同的石柱,一些石柱上站着一些蜥蜴,你的任务是让尽量多的蜥蜴逃到边界外. 每行每列中相邻石柱的距离为1,蜥蜴的跳跃距离是d,即蜥蜴可以跳到 ...