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. java.IO.EOFException异常

    错误代码为: 43 boolean booleanResult = dis.readBoolean();//dis为DateInputStream的实例 44 System.out.println(b ...

  2. 继承 多态 封装 Python面向对象的三大特性

    1. 封装: 把很多数据封装到⼀个对象中. 把固定功能的代码封装到⼀个代码块, 函数, 对象, 打包成模块. 这都属于封装的思想. 具体的情况具体分析.  那这个也可以被称为封装. 2. 继承: 两个 ...

  3. Vivado debug异常现象

    前言 bit文件和ltx文件的信号位宽不匹配问题.用了dont_touch等属性没用... WARNING: [Labtools 27-1972] Mismatch between the desig ...

  4. there is no route defined for key Agreement(react native bug记录)

    调试react native的项目有一个报错: there is no route defined for key XXXX 它发生在我调试TabNavigator选项卡路由器的时候,我把如下代码的A ...

  5. VsCode使用setting sync 同步自己的插件和设置等

    直接再 Vscode中安装就可以,然后: 1. 可以点看setting sync插件在vscode 这个时候可以按照提示进行设置(也可以参考下:https://www.cnblogs.com/kenz ...

  6. MySQL Connection--使用tcpkill杀掉MySQL活跃连接

    当MySQL连接被打满,连管理员也无法本地登录时,可以考虑使用tcpkill杀掉一些应用服务器创建的连接. CentOS 6安装tcpkill rpm安装包: libnids-1.24-1.el6.x ...

  7. WEB安全工程师整理资料

    安全产品  NESS   Nmap   AWVS Burp APPScan   chopper  sqlmap   kali linux    具体的教程可以在SEcWiki 上搜索  使用公开的漏洞 ...

  8. 数据库类型对应Java语言类型表

    下表列出了基本 SQL Server.JDBC 和 Java 编程语言数据类型之间的默认映射: SQL Server 类型 JDBC 类型 (java.sql.Types) Java 语言类型 big ...

  9. jquery复杂节点获取

    jquery.find方法 1 $("div").find(".1").css({"color":"red"," ...

  10. gensim中word2vec和其他一些向量的使用

    直接上代码吧,word2vec # test from gensim.models.word2vec import Word2Vec txt_file = open('data.txt') sente ...