MVC4+WebApi+Redis Session共享练习(下)
上一篇文章我们主要讲解了一些webApi和redis缓存操作,这篇文章我们主要说一些MVC相关的知识(过滤器和错误处理),及采用ajax调用webApi服务。
本篇例子采用的开发环境为:VS2010(sp1)、MVC4,所有的数据都是与webApi服务进行交互。
1、先来一张项目结构图

- LoginAttribute.cs为我们定义的Action过滤器,主要检测是否登陆。因为我们要测试sessioin共享,就做了一个登陆界面,存储用户名。
- BaseController.cs 公共控制器,主要重写OnException方法对错误捕捉。HomeController继承BaseController。
- ErrorController.cs 错误控制器
- LoginController.cs登陆控制器。
1.1、LoginAttribute.cs 过滤器
LoginAttribute继承ActionFilterAttribute并重写了OnActionExecuting方法,OnActionExecuting方法会先与控制器Action执行,因此我们可以在该方法中判断session是否为空。我们打开ActionFilterAttribute发现里面有四个方法OnActionExecuted、OnActionExecuting、OnResultExecuted、OnResultExecuting,不清楚其执行顺序的童鞋可以百度一下,这里就不用介绍了,下面直接看代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common; namespace MvcApplication2.Attribute
{
public class LoginAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
SessionHelper session = new SessionHelper();
if (session["user"] == null)
{
filterContext.Result = new RedirectResult("~/Login/index");
}
base.OnActionExecuting(filterContext);
}
}
}
1.2、BaseController.cs 控制器基类
BaseController继承MVC的Controller,在BaseController.cs中我们重写OnException方法进行异常处理,我们可以记录日志,跳转错误页面等,这也我们就不用每个页面写自己的异常处理了,在BaseController中我们定义了一个SessionHelper session的变量,SessionHelper为上一篇文章介绍的基于Redis的session共享,这样只要继承BaseController的页面都可以只用该变量。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common; namespace MvcApplication2.Controllers
{
public class BaseController : Controller
{
protected SessionHelper session = new SessionHelper(); public BaseController()
{ }
/// <summary>
/// 异常处理
/// </summary>
/// <param name="filterContext"></param>
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
JsonResult result = new JsonResult();
result.Data = new { type = "error", data = "请求异常" };
filterContext.Result = result;
}
else
{
filterContext.Result = new RedirectResult("~/error/index");
}
filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
}
}
1.3、LoginController.cs 为登陆控制器
该页面值需要填写用户名,然后把该用户名存到session中,这样webAPi项目中的Get方法也会获取到该session值(详细看上一篇博文)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common; namespace MvcApplication2.Controllers
{
public class LoginController : Controller
{
//
// GET: /Login/ public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult LoginIn(string user)
{
SessionHelper session = new SessionHelper();
user = Request.Form["user"];
if (!string.IsNullOrWhiteSpace(user))
{
session["user"]=user.ToString();
return RedirectToAction("index", "Home");
} return RedirectToAction("LoginIn", "Login");
} }
}
1.4、HomeController.cs 展示数据控制器
HomeController继承BaseController,并且在用[Login]过滤器作用在HomeController上,这样每一个Action前都会执行LoginAttribute,判断session值是否为空,
HomeController也继承了BaseController中的错误处理,具体看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using MvcApplication2.Attribute; namespace MvcApplication2.Controllers
{
[Login]
public class HomeController : BaseController
{
//
// GET: /Home/ public ActionResult Index()
{
ViewBag.User = session["user"].ToString();
return View();
}
public ViewResult Add()
{
return View();
}
public ViewResult edit(string id)
{
ViewBag.id = id;
return View();
}
public ActionResult LogOut()
{
session["user"] = null;
return RedirectToAction("index", "Login");
} }
}
视图页面就不介绍了,感兴趣的童鞋可以下载源代码查看。
1.5、ErrorController.cs 错误页面,这里就不介绍了
2、测试
2.1、MVC项目和WebApi部署

- webApi为上一篇介绍的webApi程序。
- webApiTest为本片介绍的MVC项目。
- 域名都是localhost,不牵扯跨域问题
2.2、上几张图片
1、登陆界面

2、点击登陆,进入首页面,记得打开Redis缓存服务

我们发现我们获取登陆页面的session值,并取到webApi服务中的数据,说明webApi项目的session也有值了,因为webApi项目的HttpResponseMessage Get()方法也做session值是否为空的判断,详见上一篇博客的说明。
好了项目就写到这里吧,我只实现了数据的获取和数据修改功能,增加和删除没有实现。如果你感兴趣欢迎交流学习。
点击下载源代码
每天学习一点点,每天进步一点点。
MVC4+WebApi+Redis Session共享练习(下)的更多相关文章
- MVC4+WebApi+Redis Session共享练习(上)
这几天生病了,也没有心情写博客,北京医院真心伤不起呀,钱不少花,病没治好,还增加了新病,哎不说了,周末还得去大医院检查一下,趁女盆友还没有回来,把前几天写的东西总结一下.本文也会接触一点webApi的 ...
- nginx tomcat负载均衡 使用redis session共享
环境准备 1.准备一台nginx服务器 ip192.168.1.133 端口81 安装过程: #首先安装依赖: yum -y install gcc-c++ yum -y install pcre p ...
- Nginx反向代理,负载均衡,redis session共享,keepalived高可用
相关知识自行搜索,直接上干货... 使用的资源: nginx主服务器一台,nginx备服务器一台,使用keepalived进行宕机切换. tomcat服务器两台,由nginx进行反向代理和负载均衡,此 ...
- Tomcat 集群 + Redis Session 共享出现 Session 瞬间失效问题
写在前面的话 写这篇博客出于公司最近要迁移到新的云上面且对之前的资源,架构做一个升级. 本来是一个不大的项目,旧环境旧一个 TOMCAT 跑起来,不过出于高可用考虑,新环境决定使用 TOMCAT 集群 ...
- tomcat redis session共享
编译redis所需要的序列化包 安装 gradle Linux & MacOS users Configure your PATH environment variable to includ ...
- redis session 共享 测试案列
下载 spring redis session demo 2.分别在不同的服务器上启动 3.nginx 安装 测试
- springboot-不同名称项目的 redis session共享
引入JAR <dependency> <groupId>org.springframework.session</groupId> <artifactId&g ...
- redis session共享中的序列化问题
今天在做session对象存入redis(set方法)时,碰到一个空指针异常,代码如下: public class CheckAccount extends HttpServlet { public ...
- Tomcat7 Redis Session共享
1.环境 服务器 centos7 tomcat 7 redis nginx 2.配置tomcat配置文件context.xml <Valve className="com.orange ...
随机推荐
- Log4Net日志的配置
<configuration> <configSections> <section name="log4net" type="log ...
- UVa 10071 - Back to High School Physics
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=s ...
- dmesg
在开机的时候你会发现有很多的讯息出现吧,例如 CPU 的形式.硬盘. 光盘型号及硬盘分割表等等,这 些信息的产生都是核心 (kernel) 在进行硬件的测试与驱动啦.要看这些讯息你可以用 dmesg ...
- html 表格的制作
表格的制作 表格<table></table> <table width="" height="" align=" ...
- 用AXIS2发布WebService的方法
Axis2+tomcat6.0 实现webService 服务端发布与客户端的调用. 第一步:首先要下载开发所需要的jar包 下载:axis2-1.6.1-war.zip http://www.apa ...
- POJ 2186-Popular Cows (图论-强联通分量Korasaju算法)
题目链接:http://poj.org/problem?id=2186 题目大意:有n头牛和m对关系, 每一对关系有两个数(a, b)代表a牛认为b牛是“受欢迎”的,且这种关系具有传递性, 如果a牛认 ...
- XML Xpath学习
Xpath是一门在xml文档中查找信息的语言. Xpath可用来在xml文档中对元素和属性进行遍历. <1>路径表达式1: 斜杠(/)作为路径内部的分隔符 同一个路径有绝对路径和相对路径两 ...
- hdu 5934 Bomb
Bomb Problem Description There are N bombs needing exploding.Each bomb has three attributes: explodi ...
- Scrum会议(Beta版本)
组名:天天向上 组长:王森 组员:张政.张金生.林莉.胡丽娜 代码地址:HTTPS:https://git.coding.net/jx8zjs/llk.git SSH:git@git.coding.n ...
- 如何在spark中读写cassandra数据 ---- 分布式计算框架spark学习之六
由于预处理的数据都存储在cassandra里面,所以想要用spark进行数据分析的话,需要读取cassandra数据,并把分析结果也一并存回到cassandra:因此需要研究一下spark如何读写ca ...