Global.asax.cs

   public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute()); } protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
//AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
EPSEmailInfoBLL.RefreshEmailSettings(); UnityHelper.UnityContainer.LoadConfiguration();
WebHelper.WebHelperImpl = UnityHelper.Resolve<IWebHelper>();
}
}

FilterConfig.cs

    public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LogAction() { });
}
}

LogAction.cs

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class LogAction : ActionFilterAttribute
{ private string actionName = string.Empty;
private Stopwatch sw = null;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
sw = Stopwatch.StartNew();
actionName = filterContext.ActionDescriptor.ActionName;
string function = actionName + " Start...";
if (filterContext.ActionParameters.Count == 0)
{
LogFormatHelper.LogRequestParams(function);
}
else
{
object[] objs = new object[filterContext.ActionParameters.Count];
int i = 0;
foreach( var dic in filterContext.ActionParameters){
objs[i++] = dic.Value;
}
LogFormatHelper.LogRequestParams(function, objs);
}
base.OnActionExecuting(filterContext);
} public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
string function = actionName + " End";
StringBuilder sb = new StringBuilder();
foreach (var key in filterContext.RouteData.Values.Keys)
{
sb.AppendFormat("{0} = {1}", key, filterContext.RouteData.Values[key]).AppendLine();
}
string str = filterContext.RouteData.Values.ToString();
LogFormatHelper.LogRequestParams(function, sw.Elapsed , sb.ToString() ); if (filterContext.Exception != null)
{
LogFormatHelper.LogServiceError(filterContext.Exception, actionName);
} } }

CheckLoginAttribute.cs

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class CheckLogin : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session != null)
{
if (filterContext.HttpContext.Session.IsNewSession)
{
//LogFormatHelper.LogRequestParams("filterContext.HttpContext.Session.IsNewSession");
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "Account", Action = "Login" }));
}
}
} }

AccountController.cs

    [RequireHttps]
#endif
[Authorize]
[InitializeSimpleMembership]
[LogAction]
public class AccountController : Controller
{
public AccountController()
: this(new FormsAuthenticationService(), new UserAuthenticator())
{
//this.FormsAuth = new FormsAuthenticationService();
}
}

NoResubmitAttribute.cs

    [AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class NoResubmitAttribute : ActionFilterAttribute
{
private static readonly string HttpMehotdPost = "POST";
private static readonly string prefix = "postFlag";
private string nameWithRoute; public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controllerContext = filterContext.Controller.ControllerContext;
if (!controllerContext.IsChildAction)
{
var request = controllerContext.HttpContext.Request;
var session = controllerContext.HttpContext.Session;
nameWithRoute = generateNameWithRoute(controllerContext);
int sessionFlag = session[nameWithRoute] == null ? 0 : (int)session[nameWithRoute];
int requestFlag = string.IsNullOrEmpty(request.Form[nameWithRoute]) ? 0 : int.Parse(request.Form[nameWithRoute]);
// get or normal post: true;
bool isValid = !IsPost(filterContext) || sessionFlag == requestFlag;
if (sessionFlag == int.MaxValue)
{
sessionFlag = -1;
}
session[nameWithRoute] = ++sessionFlag;
if (!isValid)
{
filterContext.Result = new RedirectResult(GenerateUrlWithTimeStamp(request.RawUrl));
return;
}
}
base.OnActionExecuting(filterContext);
} /// <summary>
/// Modify the url to avoid issue:
/// When Redirect to itself in a F5 Refresh, the redirect doesn't work in client browser sometimes.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string GenerateUrlWithTimeStamp(string url)
{
return string.Format("{0}{1}timeStamp={2}", url, url.Contains("?") ? "&" : "?", (DateTime.Now - DateTime.Parse("2010/01/01")).Ticks);
} private bool IsPost(ActionExecutingContext filterContext)
{
return filterContext.HttpContext.Request.HttpMethod == HttpMehotdPost;
} private string generateNameWithRoute(ControllerContext controllerContext)
{
StringBuilder sb = new StringBuilder(prefix);
foreach (object routeValue in controllerContext.RouteData.Values.Values)
{
sb.AppendFormat("_{0}", routeValue);
}
return sb.ToString();
} public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext); if (!filterContext.IsChildAction && !(filterContext.Result is RedirectResult))
{
//string format = "<script type='text/javascript'>$(function () [[ $('form').each(function()[[$('<input type=hidden id={0} name={0} value={1} />').appendTo($(this));]])]]); </script>";
string format = "<script type='text/javascript'> var forms = document.getElementsByTagName('form'); for(var i = 0; i<forms.length; i++)[[var ele = document.createElement('input'); ele.type='hidden'; ele.id=ele.name='{0}'; ele.value='{1}'; forms[i].appendChild(ele);]] </script>";
string script = string.Format(format, nameWithRoute, filterContext.HttpContext.Session[nameWithRoute]).Replace("[[", "{").Replace("]]", "}");
filterContext.HttpContext.Response.Write(script);
}
}
}

[ValidateAntiForgeryToken]

EmailAttribute.cs

 public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute()
: base("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
{
ErrorMessage = "The field {0} is an invalid email address.";
}
}

VS - ActionFilterAttribute的更多相关文章

  1. .NET WebAPI 用ActionFilterAttribute实现token令牌验证与对Action的权限控制

    项目背景是一个社区类的APP(求轻吐...),博主主要负责后台业务及接口.以前没玩过webAPI,但是领导要求必须用这个(具体原因鬼知道),只好硬着头皮上了. 最近刚做完权限这一块,分享出来给大家.欢 ...

  2. 使用ActionFilterAttribute进行重定向注意事项

    1.分部视图方法不能添加该特性,会报子方法不能重定向操作的错误 2.必须用给filterContext.Result赋值的方法进行重定向,而不能用filterContext.HttpContext.R ...

  3. mvc 4 ActionFilterAttribute 特性,进行权限验证

    权限验证: /// <summary> /// 管理员身份验证 /// </summary> public class BasicAuthenticationAttribute ...

  4. 【原创】.NET Web API之filter ActionFilterAttribute 过滤器使用

    1.在filter类里面引用,与MVC里面的不同 using System.Web.Http.Controllers; using System.Web.Http.Filters; 2.filter类 ...

  5. mvc通过ActionFilterAttribute做登录检查

    1.0 创建Attribute using System; using System.Collections.Generic; using System.Linq; using System.Web; ...

  6. Web API Filter ActionFilterAttribute 使用

    WebApi 提供两种过滤器的类型: 1.ActionFilterAttribute 2.exceptionFilterAttribute 两个类都是抽象类,ActionFilter 主要实现执行请求 ...

  7. mvc5权限管理(简单登录):ActionFilterAttribute

    效果图: 1.控制器 public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(User ...

  8. MVC权限验证之ActionFilterAttribute

    参考:http://www.cnblogs.com/waitingfor/archive/2011/12/27/2303784.html ActionFilterAttribute是Action过滤类 ...

  9. MVC中利用ActionFilterAttribute过滤关键字

    在开发过程中,有时候会对用户输入进行过滤,以便保证平台的安全性.屏蔽的方法有很多种,但是今天我说的这种主要是利用MVC中的ActionFilterAttribute属性来实现.由于MVC天然支持AOP ...

  10. ASP.NET MVC ActionFilterAttribute的执行顺序

    http://diaosbook.com/Post/2014/6/3/execution-order-of-actionfilter-aspnet-mvc ASP.NET MVC里面我们要自定义Act ...

随机推荐

  1. leetcode tree相关题目总结

    leetcode tree相关题目小结 所使用的方法不外乎递归,DFS,BFS. 1. 题100 Same Tree Given two binary trees, write a function ...

  2. go 语言学习 ---解析xml

    实例1 //main package main import ( "bytes" "encoding/xml" "fmt" "io ...

  3. C# vb .net实现羽化效果

    在.net中,如何简单快捷地实现Photoshop滤镜组中的羽化效果呢?答案是调用SharpImage!专业图像特效滤镜和合成类库.下面开始演示关键代码,您也可以在文末下载全部源码: 设置授权 第一步 ...

  4. 主机与虚拟机ping不通问题

    在win10 上利用vm安装linux虚拟机,物理机与虚拟机之间不能ping通,除了检查物理机与虚拟机防火墙状态外,还要注意物理机设置的ip与虚拟机设置的ip,要在同一个ip段

  5. Java调用WebService方法总结(1)--准备工作

    WebService是一种跨编程语言.跨操作系统平台的远程调用技术,已存在很多年了,很多接口也都是通过WebService方式来发布的:本系列文章主要介绍Java调用WebService的各种方法,使 ...

  6. MySQL数据库使用时注意事项

    MySQL数据库使用时注意事项 建表的角度上 1.合理安排表关系 2.尽量把固定长度的字段放在前面 3.尽量使用char 代替varchar 4.分表:水平分和垂直分 在使用sql语句的时候 1.尽量 ...

  7. Java经典逻辑编程50题 (转)

    注: 转自https://blog.csdn.net/Alias_fa/article/details/52985112  (摘了题目部分和部分分析,想看原作代码的见原作链接) [程序1] 題目:古典 ...

  8. Struts框架笔记03_OGNL表达式与值栈

    目录 1. OGNL 1.1 OGNL概述 1.1 什么是OGNL 1.1.2 OGNL的优势 1.1.2 OGNL使用的要素 1.2 OGNL的Java环境入门[了解] 1.2.1 访问对象的方法 ...

  9. Vue 文档Demo01

    Vue 1. Vue 基础 1. 声明式渲染 1. v-bind <!DOCTYPE html> <html> <head> <meta charset=&q ...

  10. Android笔记(五十三) 利用有道OPENAPI做简单的翻译demo

    先去 http://fanyi.youdao.com/openapi?path=data-mode 申请开发者key 有道api会自动将申请的单词翻译并返回为xml或者json格式,我们所需要做的就是 ...