一、使用MVC中的Filter来对Session进行验证
(1)方法1:
public class MyAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var loginUser = filterContext.HttpContext.Session["User"];
//When user has not login yet
if (loginUser == null)
{
var redirectUrl = ConstantProvider.LoginURL + "?RedirectPath=" + filterContext.HttpContext.Request.Url;
filterContext.Result = new RedirectResult(redirectUrl);
return;
}
}
}
(2)方法二:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GiftWeb.Controllers
{
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (filterContext.HttpContext.Session["sysuserInfo"] == null)
{
string currentUrl = filterContext.HttpContext.Request.RawUrl;
currentUrl = HttpUtility.UrlEncode(currentUrl);
filterContext.HttpContext.Response.Redirect("/Login/Index?returnUrl="+currentUrl);
}
}
}
}
二、对于Ajax请求的中,Session失效的处理
Ajax请求中,如果遇到session过期,使用上面的方法是不能够达到效果的。实现的思路是,如果发现是Ajax请求,就返回 特定格式的Json数据 ,客户端对于这个数据进行处理,发现有Session失效的情况,就跳转到登录页面。
首先,扩展我们的MyAuthorizeAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class MyAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var loginUser = filterContext.HttpContext.Session["User"];
//When user has not login yet
if (loginUser == null)
{
var redirectUrl = ConstantProvider.LoginURL + "?RedirectPath=" + filterContext.HttpContext.Request.Url;
if(!filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new RedirectResult(redirectUrl);
}
else
{
filterContext.Result = new JsonResult
{
Data = new
{
Success = false,
Message = string.Empty,
Redirect = redirectUrl
}
};
}
return;
}
}
上面判断如果请求是来自于Ajax, 就返回一个Json Result,客户端处理的代码如下:
$.ajax({
type: "POST",
url: "@Url.ContactInfoAjax()",
success: function (msg) {
if (msg.Success) {
…….
}
if (msg.Redirect) {
window.location = msg.Redirect;
}
}
});
三、处理Session过期异常的重要性
说实话,开发人员开始项目的时候,往往关注在代码实现的功能上面,也就是程序"正常 "工作时候的状态关注的更多,而对于" 非正常 "情况下,考虑的很少。
而对于这些方面的考虑,才能让我们成为更加专业的程序员,摆脱菜鸟的处境。