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. 浅谈TSM概念、系统架构及技术发展

    NFC作为一种近距离的无线通信技术,提供了一种更直接.更安全的现场交互解决方案.它能够允许电子设备之间进行非接触式点对点数据传输,实现数据交换.访问内容与服务.有了它,手机不再只是打电话.发短信以及上 ...

  2. “我爱淘”第二冲刺阶段Scrum站立会议7

    完成任务: 完成学院分类的点击查看书籍功能,可以点击书的条目查看书的详细信息.将登陆界面以及注册发布界面完善了一下修复一些bug. 计划任务: 将书的详细信息进行完善,并且可以点击收藏以及已预订等功能 ...

  3. 代码查重工具sim

    在瞎搜东西的时候,发现了一个大牛的博客 看起来很厉害的样子...做了一个LaTeX的语法检查并给出适当的提示,上wiki上一查发现他竟然是CVS第一个版本的发明者和开发者...Dick grune这是 ...

  4. CCF——相邻数对201409-1

    问题描述 给定n个不同的整数,问这些数中有多少对整数,它们的值正好相差1. 输入格式 输入的第一行包含一个整数n,表示给定整数的个数. 第二行包含所给定的n个整数. 输出格式 输出一个整数,表示值正好 ...

  5. Halcon 笔记1

    Halcon Example位置: C:\Users\Public\Documents\MVTec\HALCON-13.0\examples 安装位置:C:\Program Files\MVTec\H ...

  6. web.py 笔记

    1.涉及到id=‘id’的情况,需要加入  vars=locals()  ,因为id在python里有id() 函数 db.delete('entries', where = 'id = $id', ...

  7. PHP实现HTML页面静态化

    随着网站的内容的增多和用户访问量的增多,无可避免的是网站加载会越来越慢,受限于带宽和服务器同一时间的请求次数的限制,我们往往需要在此时对我们的网站进行代码优化和服务器配置的优化.一般情况下会从以下方面 ...

  8. windows操作系统下载tomcat,并与eclipse进行整合

    进入Tomcat官网之后,在左边我们看到,Tomcat的有6,7,8这三个最流行的版本,我们可以点击进去下载想要的版本. 进入里面之后,可以看见有64位的和32位的,就看自己的电脑是多少位的了,如果电 ...

  9. java & maven pom

    java & maven pom https://maven.apache.org/pom.html http://www.tutorialspoint.com/maven/maven_pom ...

  10. Linux进入单用户模式(passwd root修改密码)

    进入单用户模式——passwd root修改密码 1.在grub 页面输入a,进入修改内核模式 2.在内核的结尾“/”,输入空格,在输入single,回车 3.启动系统,进入单用户模式 4.Passw ...