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 ...
随机推荐
- glReadPixels函数
GPU渲染完数据在显存,回传内存的唯一方式glReadPixels函数... glReadPixels:读取一些像素.当前可以简单理解为“把已经绘制好的像素(它可能已经被保存到显卡的显存中)读取到内存 ...
- Scrum 项目——1
广商检索页面 1) N (Need 需求) 这个页面会按一定的规律来集合广商的一些资源,包括微信公众号.教务系统登录处.宿舍报修等,是为了方便我们整个广商的学生和老师来运用.因为现在虽然有很多微信公众 ...
- 处理返回结果(XML)
var xmlHttp function showUser(str) { xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Br ...
- 动端逐渐出了许多的移动端的框架,比如Sencha Touch、JQTouch、Jquery-moblie、jqMobi等等。这些框架都有优缺点,不同的框架应用在不同的项目中。现简单阐述一下各框架的优缺点:
移动前端工作的那些事---前端制作之微信小技巧篇 (2013-11-15 15:20) 转载▼ 标签: it css3/javascript html5 webapp 手机网站搭建 分类: 前端制 ...
- C语言 malloc calloc realloc alloc 在分配内存时的 区别
malloc : 向堆申请分配内存,不初始化 calloc : 向堆申请分配内存,初始化为0 realloc: 向堆申请分配内存,可调整大小 alloc : 向栈申请内存,不需手动释放
- jquery 找不到live方法解决
http://stackoverflow.com/questions/15573645/typeerror-live-is-not-a-function
- to_char 详解
对TO_CHAR的讨论可以分为从两种类型的数据到字符的转换:DATE和NUMBER. TO_CHAR函数返回VARCHAR2数据类型的值. 1. NUMBER TO CHAR 语法: TO_CHAR( ...
- Search and Replace
function myReplace(str, before, after) { //return str; if(before[0] === before[0].toUpperCase()){ af ...
- sqlserver中,查看某个函数的调用情况
今天想在sqlserver中看看自己写的函数都被哪个函数或存储过程调用了,手工检查起来太慢了,于是在网上找一个快速的方法,分享一下. select * from sys.all_sql_modules ...
- 安装uwsgi记录
yum install gcc pip install uwsgi 报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 ... 解决: ...