MVC3 全局验证、过滤
1、首先定义一个全局类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Web.Security;
using System.Net;
using System.IO;
using ModelProject;
using System.Web.Routing;
using System.Runtime.Remoting.Contexts;
namespace UtilityBase
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
/// <summary>
/// <para> 功| 能:o自?定义?全?局?过y滤?器 </para>
/// <para> 作 者?:o韩?保新? </para>
/// <para> 创建日?期: 2011-7-25 9:39:13 </para>
/// </summary>
public class GloalMvcFiters : ActionFilterAttribute
{
public string Message { get; set; }
private const string WebService_Root = "WebServiceRoot";
/// <summary>
/// 控?制?器方?法执行D之?后执行D
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var fullName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated && !GetList().Contains(fullName))
{
//System.Web.HttpContext.Current.Response.Redirect("~/Account/LogOn", true);
filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { area = "", controller = "Account", action = "LogOn" }));
}
}
/// <summary>
/// 控制器方法执行之前执行
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//var s = "</br>控制器名称:" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName + "</br>操作方?法:o" + filterContext.ActionDescriptor.ActionName;
//filterContext.HttpContext.Response.Write(@"<br />Before Action Excute" + "\t "+ s +"\t"+ Message);
//filterContext.HttpContext.Response.End();
base.OnActionExecuting(filterContext);
}
/// <summary>
/// 视图加载完成后执行
/// </summary>
/// <param name="filterContext"></param>
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
//filterContext.HttpContext.Response.Write(@"<br />After ViewResult Excute" + "\t " + Message);
base.OnResultExecuted(filterContext);
}
/// <summary>
/// 视图加载之前执行
/// </summary>
/// <param name="filterContext"></param>
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
//filterContext.HttpContext.Response.Write(@"<br />Before ViewResult Excute" + "\t " + Message);
base.OnResultExecuting(filterContext);
}
private List<string> GetList()
{
List<string> list = new List<string>();
list.Add("WebUI.Controllers.AccountController");
list.Add("WebUI.Controllers.ErrorController");
return list;
}
}
}
2、Global.asax中注册
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalFilters.Filters.Add(new UtilityBase.GloalMvcFiters() { Message = "Gloable" });
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}