首页 > 代码库 > cs-Filters

cs-Filters

ylbtech-Unitity: cs-Filters

HealthcareAuthorizeAttribute.cs

HealthcareHandleErrorAttribute.cs

HealthcareJSONHandleErrorAttribute.cs

1.A,效果图返回顶部
 
1.B,源代码返回顶部
1.B.1,HealthcareAuthorizeAttribute.cs
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 = "79", EmployeeName = "Tom", LoginId = "2", LoginName = "Tom.xu",            OrganizationID="90",OrganizationCode="01",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 == 0)                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[0];        }        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()            };        }    }}
View Code

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;        }    }}
View Code

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 = http://www.mamicode.com/resultData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };                filterContext.ExceptionHandled = true;            }            base.OnException(filterContext);        }    }}
View Code

1.B.4,

1.C,下载地址返回顶部

 

warn作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

cs-Filters