MVC4+WebApi+Redis Session共享练习(上)

这几天生病了,也没有心情写博客,北京医院真心伤不起呀,钱不少花,病没治好,还增加了新病,哎不说了,周末还得去大医院检查一下,趁女盆友还没有回来,把前几天写的东西总结一下。本文也会接触一点webApi的东东,自己最近也一直在看,算是入门了吧。本文用到的知识点有MVC4、knockout.jsEntityFramework、WebApi、Redis缓存基于Redis缓存的Session共享,都是很基础的操作,MVC我会介绍过滤器及错误捕捉,EntityFramework增删改数据,WebApi做为数据通信以及Redis的基本缓存操作等。

如果你对这些知识还不太熟悉,请打开连接阅读前几篇文章。http://www.cnblogs.com/lc-chenlong/

本文参考:

http://www.cnblogs.com/artech/archive/2012/05/14/web-api-demo.html(蒋金楠)

http://www.cnblogs.com/rohelm/p/3195750.html(webAPI入门讲解)

本文主要实现以下功能:

  1. MVCweb程序与WebApi实现数据通信及Session共享(两个分部署)
  2. MVC过滤器及错误捕捉
  3. Redis缓存操作

通过一个学生信息的管理来实现该项目。本人对webApi也是入门级别,如果过得不对的欢迎指正,也欢迎分享学习资料。

1、我们先介绍一下WebApi项目,项目结构如下图

  1. 其中Common项目为自定义的Session,详细请参见http://www.cnblogs.com/lc-chenlong/p/3221003.html
  2. MvcWebApi要引用Common项目
  3. MvcWebApi项目 ValuesController.cs为数据的增删改查及Redis缓存操作
  4. DbHelper.cs为我们的数据库上下文
  5. Students.cs为学生实体类。

1.1、Students.cs实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MvcWebApi.Models
{
    [Table("tb_Students", Schema = "dbo")]//关联数据表 dbo.tb_Students
    public class Students
    {
        [Key]
        public string Num { get; set; }
        [MaxLength(10),Required(ErrorMessage="姓名不能为空")]
        [Column(TypeName = "nvarchar")]
        public string Name { get; set; }
        public int Age { get; set; }
        [MaxLength(10)]
        [Column(TypeName = "varchar")]
        public string Sex { get; set; }
        [MaxLength(50)]
        public string Class { get; set; }
    }
}
View Code

1.2、DbHelper.cs数据库上下文

该文件主要定义数据库的上下文,我对EF用的海曙不够熟练,最近也一直在看,推荐一个人的博客,是一个EF学习的系列,讲的还不错。http://www.cnblogs.com/wlflovenet/archive/2011/12/30/EF11.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace MvcWebApi.Models
{
    public class DbHelper : DbContext
    {
        public DbHelper()
            : base("strConn")
        {
            //自动创建表,如果Entity有改到就更新到表结构
            Database.SetInitializer<DbHelper>(new MigrateDatabaseToLatestVersion<DbHelper, ReportingDbMigrationsConfiguration>());
        }
        public DbSet<Students> Students { get; set; }
    }
    internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<DbHelper>
    {
        public ReportingDbMigrationsConfiguration()
        {
            AutomaticMigrationsEnabled = true;//任何Model Class的修改將會直接更新DB
            AutomaticMigrationDataLossAllowed = true;
        }
    }
}
View Code

 

1.3、ValuesController.cs数据操作控制器

在控制器中我们定义了增删改查的基本方法,及Redis的操作,该控制器中只有Get()方法判断了session是否为空,这里只是为了验证一下session的值是否传递过来了。本知识点参照文章:http://www.cnblogs.com/newton/p/3238082.html

看代码之前下介绍一下Redis的一个操作。1、Redise.AddEntityToList<Students>("stuList", stu);我们定义了一个缓存键位stuList的缓存列表,该缓存列表存储的是Students实体,而不是把List<Students> stu存进去。2、Redise.AddEntityToList<Students>("stuList", stu);将单个stu对象存进缓存链表中。3、Redise.GetList<Students>("stuList")从缓存中获取列表。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MvcWebApi.Models;
using Common;
using System.Data;

namespace MvcWebApi.Controllers
{
    public class ValuesController : ApiController
    {
        SessionHelper session = new SessionHelper();
        RedisHelper Redise = new RedisHelper();
        // GET api/values

        public HttpResponseMessage Get()
        {
            //判断session的值是否传递过来
            if (session["user"] == null)
            {
                return Request.CreateResponse(HttpStatusCode.OK, new { type="error",data="session为空,清先登陆"});
            }
       //从stuList缓存链表获取数据
var stuList = Redise.GetList<Students>("stuList"); if (stuList == null || stuList.Count()==0) { using (DbHelper db = new DbHelper()) { stuList = db.Students.ToList(); //创建stuList缓存链表 Redise.AddList<Students>("stuList", stuList); } } var data = new { type = "success", data = stuList }; return Request.CreateResponse(HttpStatusCode.OK, data); //db.Students.ToList(); } // GET api/values/5 public Students Get(string id) { Students stu = Redise.GetList<Students>("stuList").Where(it => it.Num == id).FirstOrDefault(); if (stu == null) { using (DbHelper db = new DbHelper()) { stu=db.Students.Where(it => it.Num == id).FirstOrDefault(); if (stu != null) { //向stuList缓存链表中添加实体 Redise.AddEntityToList<Students>("stuList", stu); } } } return stu; } // POST api/values public void Post([FromBody] Students stu) { } // PUT api/values/5 public HttpResponseMessage Put([FromBody] Students stu) { Students RedStu = Redise.GetList<Students>("stuList").Where(it => it.Num == stu.Num).FirstOrDefault(); Redise.RemoveEntityFromList<Students>("stuList", RedStu); Redise.AddEntityToList("stuList", stu); using (DbHelper db = new DbHelper()) { db.Entry(stu).State = EntityState.Modified; db.SaveChanges(); } return Request.CreateResponse(HttpStatusCode.OK, new { type = "success" }); } // DELETE api/values/5 public void Delete(int id) { } } }

 

介绍一下下面代码返回的json数据格式
var data = new { type = "success", data = stuList };
return Request.CreateResponse(HttpStatusCode.OK, data);
数据格式为:
{"type":"success",data:[{},{},{}]}

 

今天就写到这里吧。明天继续写MVC调用WebAPi。源代码下一篇写完奉上。

每天学习一点点,每天进步一点点

 

posted @ 2013-08-08 20:41  Eric.Chen  阅读(9761)  评论(12编辑  收藏  举报
作者:Eric.Chen
出处:https://www.cnblogs.com/lc-chenlong
如果喜欢作者的文章,请关注“写代码的猿”订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。