ASP.NET MVC5中使用IActionFilter拦截器陷阱注意

ASP.NET MVC5中使用IActionFilter拦截器陷阱注意

584发表于2019-04-12

之前写过一文:

ASP.NET MVC5中使用IAuthenticationFilter来验证登录和权限的陷井,你知道吗?

今天发现使用,FilterAttribute, IActionFilter来做权限拦截也有这个问题。使用不当,照样会调用Action里面方法,你可以打个断点检查一下你的代码。

下面是我写的伪代码可以参考:

public class AuthorizeSessionAttribute : FilterAttribute, IActionFilter
{
	public void OnActionExecuting(ActionExecutingContext filterContext)
	{
		var user = LoginStateHelper.CurrentUser;
		var isAjax = filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
        var accept = filterContext.HttpContext.Request.Headers["Accept"] ?? "";
		if (user == null)
		{
			if (isAjax || accept.IndexOf("application/json") > -1)
			{
				var result = new CommonResult();
				result.Message = "登录过期请,请重新登录!";
				result.State = 0;
				result.Data = "/Account/Logon";
				filterContext.Result = new JsonResult() { Data = result, ContentType = "application/json; charset=utf-8" };
				//filterContext.HttpContext.Response.Write(str);
				//filterContext.HttpContext.Response.End();
			}
			else
				filterContext.Result = new RedirectResult("/Account/Logon");
		}
		else
		{
			if (权限检查,若无权限)
			{
				if (isAjax || accept.IndexOf("application/json") > -1)
				{
					var result = new CommonResult();
					result.Message = "无权限";
					filterContext.Result = new JsonResult() { Data = result, ContentType = "application/json; charset=utf-8" };
				}
				else
				{
					filterContext.Result = new ContentResult() { Content = "无权限"; };
				}
			}
			
		}
	}
	
	public void OnActionExecuted(ActionExecutedContext filterContext)
	{
		
	}
}

注意:

若验证不通过一定要为filterContext.Result赋值。可以是常用以下类型作为返回:

跳转:RedirectResult

json数据:JsonResult

纯文本:ContentResult


小编蓝狐