cs-Filters
ylbtech-Unitity: cs-Filters |
HealthcareAuthorizeAttribute.cs
HealthcareHandleErrorAttribute.cs
HealthcareJSONHandleErrorAttribute.cs
1.A,效果图返回顶部 |
1.B,源代码返回顶部 |
using Healthcare.Framework.Web.Mvc.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Security; namespace Healthcare.Framework.Web.Mvc
{
public class HealthcareAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
//So now we are validating for secure part of the application
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = filterContext.ActionDescriptor.ActionName;
var controllerType = filterContext.Controller; //skip authorization for specific part of application, which have deliberately marked with [SkipAuthorizaion] attribute
if (filterContext.ActionDescriptor.IsDefined(typeof(SkipAuthorizaionAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipAuthorizaionAttribute), true))
{
return;
}
//filterContext.HttpContext.Session["User"] = new Users()
//{
// EmployeeId = "79",
// EmployeeName = "Tom",
// LoginId = "2",
// LoginName = "Tom.xu",
// OrganizationID = "90",
// OrganizationCode = "01",
// OrganizationName = "总院"
//};
#if DEVBOX
filterContext.HttpContext.Session["User"] = new Users() { EmployeeId = "", EmployeeName = "Tom", LoginId = "", LoginName = "Tom.xu",
OrganizationID="",OrganizationCode="",OrganizationName="总院"};
#endif if( filterContext.HttpContext==null)
{
throw new MvcException("用户登录过期,请重新登录!");
} if (filterContext.HttpContext == null
|| filterContext.HttpContext.Session == null
|| filterContext.HttpContext.Session["User"] == null
|| !(filterContext.HttpContext.Session["User"] is Users)
|| (filterContext.HttpContext.Session["User"] as Users) == null )
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
throw new MvcException ("用户登录过期,请刷新窗口以后重新登录!");
}
else
{
filterContext.HttpContext.Session["RequestOldUrl"] = filterContext.HttpContext.Request.Url;
//filterContext.HttpContext.Session["RequestOldUrl"] = filterContext.HttpContext.Request.UrlReferrer; filterContext.Result = new RedirectResult("~/Account/LogOn"); //new HttpUnauthorizedResult("用户未登陆!");
return;
}
} var user = filterContext.HttpContext.Session["User"] as Users; if (filterContext.ActionDescriptor.IsDefined(typeof(PermissionsAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(PermissionsAttribute), true))
{
var controllerAttribute = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionsAttribute), true).Cast<PermissionsAttribute>().FirstOrDefault();
var actionAttribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionsAttribute), true).Cast<PermissionsAttribute>().FirstOrDefault();
if (!IsUserAuthorized(user, controllerAttribute, actionAttribute))
{
throw new NoPermissionException("用户无权进行操作!");
}
} // base.OnAuthorization(filterContext);
} private static bool IsUserAuthorized(Users user, PermissionsAttribute controllerPermissions, PermissionsAttribute actionPermissions)
{
var effective = PermissionsAttribute.Merge(controllerPermissions, actionPermissions); if (effective.Allow.Length == )
return false; bool isUserAuthorized = effective.Allow.All(user.HasPermission);
return isUserAuthorized;
}
} [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class SkipAuthorizaionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class PermissionsAttribute : Attribute
{
public PermissionsAttribute(params string[] allow)
{
Allow = allow ?? new string[];
} public string[] Allow { get; private set; } public static PermissionsAttribute Merge(params PermissionsAttribute[] permissions)
{
if (permissions == null)
{
return new PermissionsAttribute();
} var allNotNullPermissions = permissions.Where(p => p != null); if (!allNotNullPermissions.Any())
{
return new PermissionsAttribute();
} return new PermissionsAttribute
{
Allow = allNotNullPermissions.Aggregate(new List<string>(),
(list, permissionsAttribute) =>
{
list.AddRange(permissionsAttribute.Allow);
return list;
}).ToArray()
};
}
}
}
1.B.2,HealthcareHandleErrorAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web;
using Elmah; namespace Healthcare.Framework.Web.Mvc
{
public class HealthcareHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
// private Lazy<ILogger> logger = new Lazy<ILogger>(() => KernelContainer.Kernel.Get<ILogger>()); public virtual void OnException(ExceptionContext filterContext)
{
string controllerName = filterContext.RouteData.Values["Controller"] as string;
string actionName = filterContext.RouteData.Values["action"] as string; if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = "Error",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData,
//ViewData["aa"] = filterContext.Controller.ViewBag.asd
};
filterContext.ExceptionHandled = true;
} if (!filterContext.ExceptionHandled
|| TryRaiseErrorSignal(filterContext)
|| IsFiltered(filterContext))
return; if (filterContext.ExceptionHandled)
{
if (TryRaiseErrorSignal(filterContext) || IsFiltered(filterContext))
return; LogException(filterContext); //自定义日志
//Logging.ErrorLoggingEngine.Instance().Insert("action:" + actionName + ";sessionid:" + (filterContext.HttpContext.GetHttpSessionId()), filterContext.Exception);
} } private static bool TryRaiseErrorSignal(ExceptionContext context)
{
var httpContext = GetHttpContextImpl(context.HttpContext);
if (httpContext == null)
return false;
var signal = ErrorSignal.FromContext(httpContext);
if (signal == null)
return false;
signal.Raise(context.Exception, httpContext);
return true;
} private static bool IsFiltered(ExceptionContext context)
{
var config = context.HttpContext.GetSection("elmah/errorFilter")
as ErrorFilterConfiguration; if (config == null)
return false; var testContext = new ErrorFilterModule.AssertionHelperContext(
context.Exception,
GetHttpContextImpl(context.HttpContext));
return config.Assertion.Test(testContext);
} private static void LogException(ExceptionContext context)
{
var httpContext = GetHttpContextImpl(context.HttpContext);
var error = new Error(context.Exception, httpContext);
ErrorLog.GetDefault(httpContext).Log(error);
} private static HttpContext GetHttpContextImpl(HttpContextBase context)
{
return context.ApplicationInstance.Context;
}
}
}
1.B.3,HealthcareJSONHandleErrorAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc; namespace Healthcare.Framework.Web.Mvc
{
public class HealthcareJSONHandleErrorAttribute : HealthcareHandleErrorAttribute
{
public HealthcareJSONHandleErrorAttribute()
: base()
{
} public override void OnException(ExceptionContext filterContext)
{
Controller controller = filterContext.Controller as Controller;
Exception exception = filterContext.Exception; if (controller != null)
{
controller.Response.TrySkipIisCustomErrors = true;
controller.Response.StatusCode = (int)HttpStatusCode.AjaxErrorResult; object resultData;
if (exception.GetType() == typeof(System.TimeoutException))
{
resultData = new
{
DisplayMessage = "系统超时",
DetailMessage = exception.ToString(),
};
}
else
{
MvcException mvcException = exception as MvcException; if (mvcException != null)
{
resultData = mvcException.GetClientResultData();
}
else
{
resultData = new
{
DisplayMessage = "未知错误",
DetailMessage = exception.ToString(),
};
}
}
filterContext.Result = new JsonResult { Data = resultData, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.ExceptionHandled = true;
} base.OnException(filterContext);
}
}
}
1.B.4,
1.C,下载地址返回顶部 |
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |
cs-Filters的更多相关文章
- MVC中的过滤器
authour: chenboyi updatetime: 2015-05-09 09:30:30 friendly link: 目录: 1,思维导图 2,过滤器种类(图示) 3,全局过滤器 ...
- 7天玩转 ASP.NET MVC
在开始时请先设置firefox中about:config中browser.cache.check_doc_frequecy设置为1,这样才能在关闭浏览器时及时更新JS 第一.二天的内容与之前的重复,这 ...
- System.Web.Mvc.Filters.IAuthenticationFilter.cs
ylbtech-System.Web.Mvc.Filters.IAuthenticationFilter.cs 1.程序集 System.Web.Mvc, Version=5.2.3.0, Cultu ...
- SharePoint 2007 Full Text Searching PowerShell and CS file content with SharePoint Search
1. Ensure your site or shared folder in one Content Source. 2. Add file types. 3. The second step in ...
- Global.asax.cs介绍
转载 http://www.cnblogs.com/tech-bird/p/3629585.html ASP.NET的配置文件 Global.asax--全局应用程序文件 Web.config--基 ...
- aspx.cs上传文件
aspx.cs文件 using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...
- MVC中的Startup.Auth.cs、BundleConfig.cs、FilterConfig.cs和RouteConfig.cs
一.MVC中的Startup.Auth.cs.BundleConfig.cs.FilterConfig.cs和RouteConfig.cs四个文件在app_start中 <1>Bundle ...
- ASP.NET Core 菜鸟之路:从Startup.cs说起
1.前言 本文主要是以Visual Studio 2017 默认的 WebApi 模板作为基架,基于Asp .Net Core 1.0,本文面向的是初学者,如果你有 ASP.NET Core 相关实践 ...
- ASP.NET Core 2 学习笔记(十四)Filters
Filter是延续ASP.NET MVC的产物,同样保留了五种的Filter,分别是Authorization Filter.Resource Filter.Action Filter.Excepti ...
- .net core MVC 通过 Filters 过滤器拦截请求及响应内容
前提: 需要nuget Microsoft.Extensions.Logging.Log4Net.AspNetCore 2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...
随机推荐
- HDU 2554 N对数的排列问题 ( 数学 )
题目链接 Problem Description 有N对双胞胎,他们的年龄分别是1,2,3,--,N岁,他们手拉手排成一队到野外去玩,要经过一根独木桥,为了安全起见,要求年龄大的和年龄小的排在一起,好 ...
- NYOJ 127 星际之门(一) (数学)
题目链接 描述 公元3000年,子虚帝国统领着N个星系,原先它们是靠近光束飞船来进行旅行的,近来,X博士发明了星际之门,它利用虫洞技术,一条虫洞可以连通任意的两个星系,使人们不必再待待便可立刻到达目的 ...
- bzoj 2705 数学 欧拉函数
首先因为N很大,我们几乎不能筛任何东西 那么考虑设s(p)为 gcd(i,n)=p 的个数,显然p|n的时候才有意义 因为i与n的gcd肯定是n的因数,所以那么可得ans=Σ(p*s(p)) 那么对于 ...
- 用python写爬虫笔记(一)
https://bitbucket.org/wswp/code http://example.webscraping.com http://www.w3schools.com selenium.g ...
- swift对比object-c
http://www.cocoachina.com/bbs/read.php?tid=204294 WWDC 2014上苹果再次惊世骇俗的推出了新的编程语言SWIFT( 雨燕 ), 这个消息会前没有半 ...
- linux下源码安装netcat
linux下源码安装netcat http://blog.chinaunix.net/uid-20783755-id-4211230.html 1,下载netcat源码,netcat-0.7.1-13 ...
- mysql内连接、左连接、右连接举例说明
如下: CREATE TABLE tb ( id INT PRIMARY KEY, NAME VARCHAR (20) ) ; CREATE TABLE ta ( id INT PRIMARY KEY ...
- 4.shell预定义变量
就是shell设计者实现预定好的变量,可以直接在shell脚本中使用$$:当前进程的进程号(pid)$!:后台运行的最后一个进程的进程号(pid)$?:最后一次执行的命令的返回状态,如果这个变量的值为 ...
- [ Openstack ] Openstack-Mitaka 高可用之 Mariadb-Galera集群部署
目录 Openstack-Mitaka 高可用之 概述 Openstack-Mitaka 高可用之 环境初始化 Openstack-Mitaka 高可用之 Mariadb-Galera集群 ...
- facets学习(1):什么是facets
ML 数据集可以包含数亿个数据点,每个数据点由数百(甚至数千)的特征组成,几乎不可能以直观的方式了解整个数据集.为帮助理解.分析和调试 ML 数据集,谷歌开源了 Facets,一款可视化工具. Fac ...