MVC4+WebApi+Redis Session共享練習(下)


上一篇文章我們主要講解了一些webApi和redis緩存操作,這篇文章我們主要說一些MVC相關的知識(過濾器和錯誤處理),及采用ajax調用webApi服務。

本篇例子采用的開發環境為:VS2010(sp1)、MVC4,所有的數據都是與webApi服務進行交互。

1、先來一張項目結構圖

  1. LoginAttribute.cs為我們定義的Action過濾器,主要檢測是否登陸。因為我們要測試sessioin共享,就做了一個登陸界面,存儲用戶名。
  2. BaseController.cs 公共控制器,主要重寫OnException方法對錯誤捕捉。HomeController繼承BaseController。
  3. ErrorController.cs 錯誤控制器
  4. 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");
        }

    }
}
View Code

 

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部署

 

  1. webApi為上一篇介紹的webApi程序。
  2. webApiTest為本片介紹的MVC項目。
  3. 域名都是localhost,不牽扯跨域問題

2.2、上幾張圖片

1、登陸界面

2、點擊登陸,進入首頁面,記得打開Redis緩存服務

我們發現我們獲取登陸頁面的session值,並取到webApi服務中的數據,說明webApi項目的session也有值了,因為webApi項目的HttpResponseMessage Get()方法也做session值是否為空的判斷,詳見上一篇博客的說明。

好了項目就寫到這里吧,我只實現了數據的獲取和數據修改功能,增加和刪除沒有實現。如果你感興趣歡迎交流學習。

點擊下載源代碼

每天學習一點點,每天進步一點點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM