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()
            };
        }
    }
}

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/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
时间: 2024-12-21 04:49:23

cs-Filters的相关文章

7天玩转 ASP.NET MVC

在开始时请先设置firefox中about:config中browser.cache.check_doc_frequecy设置为1,这样才能在关闭浏览器时及时更新JS 第一.二天的内容与之前的重复,这里不再重复 弱类型ViewData 中的数据类型是Object.所以我们在使用之前需要进行正确的类型转换,没有类型安全 public ActionResult GetView() { Employee emp = new Employee(); emp.FirstName = "Sukesh&quo

Global.asax.cs介绍

转载  http://www.cnblogs.com/tech-bird/p/3629585.html ASP.NET的配置文件 Global.asax--全局应用程序文件 Web.config--基于XML的应用程序配置文件 global.asax是一个文本文件,它提供全局可用代码.这些代码包括应用程序的事件处理程序以及会话事件.方法和静态变量.有时该文件也被称为应用程序文件. global.asax文件中的任何代码都是它所在的应用程序的一部分.每个应用程序在其根目录下只能有一个global.

ASP.NET Core 菜鸟之路:从Startup.cs说起

1.前言 本文主要是以Visual Studio 2017 默认的 WebApi 模板作为基架,基于Asp .Net Core 1.0,本文面向的是初学者,如果你有 ASP.NET Core 相关实践经验,欢迎在评论区补充.与早期版本的 ASP.NET 对比,最显著的变化之一就是配置应用程序的方式, Global.asax.FilterConfig.cs 和 RouteConfig.cs 统统消失了,取而代之的是 Program.cs 和 Startup.cs.Program.cs 作为 Web

Android官方文档之App Components(Intents and Intent Filters)

Android应用框架鼓励开发者在开发应用时重用组件,本文将阐述如何用组件构建应用程序以及如何用intent将组件联系起来. 如需阅读官方原文,请您点击这个链接: <App Components>. 您还可以参考这些博文: <Using DialogFragments> <Fragments For All> <Multithreading For Performance> 以及这些Training: <Managing the Activity Li

mvc4 利用filters特性来 实现自己的权限验证 之二

刚开始摸索C# MVC,也只是按图索骥,对C#的特性不是很懂,耐心看完相关文章,对特性的使用有了进一步理解. 1.特性类的命名规范:特性也是一个类,必须继承于System.Attribute类,命名规范为“类名”+Attribute.不管是直接还是间接继承,都会成为一个特性类,特性类的声明定义了一种可以放置在声明之上新的特性. 2.特性的使用:[特性类名(不需要后缀Attribute)(公共属性=值, 公共属性=值...)]放置于类.方法.字段.属性.结构体...前修饰. 如: //在Perso

斯坦福CS课程列表

http://exploredegrees.stanford.edu/coursedescriptions/cs/ CS 101. Introduction to Computing Principles. 3-5 Units. Introduces the essential ideas of computing: data representation, algorithms, programming "code", computer hardware, networking, s

CS文件类头注释

1.修改unity生成CS文件的模板(模板位置:Unity\Editor\Data\Resources\ScriptTemplates 文件名:81-C# Script-NewBehaviourScript.cs) 本人将模板修改为如下图(红框内的内容) 备注:在"#"之间的为可替换的参数 2.修改模板可替换参数,在工程项目Asset文件夹在创建Editor文件 在文件夹下添加AddFileHeadComment.cs文件 内容如下 参数内容根据个人需求修改

CS 和 BS 的区别和优缺点

bs是浏览器(browser)和服务器(server) cs是静态客户端程序(client)和服务器(server) 区别在于,虽然同样是通过一个程序连接到服务器进行网络通讯,但是bs结构的,客户端运行在浏览器里,比如你看百度,就是通过浏览器.还有一些bs结构的应用,比如中国电信,以及一些电子商务平台.用bs结构的好处是,不必专门开发一个客户端界面,可用asp,php,jsp等比较快速开发web应用的程序开发. cs结构的,要做一个客户端.网络游戏基本上大多是cs结构,比如你玩传奇,要专门开个传

微软SQLHelper.cs类 中文版

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Xml; using System.Collections; namespace LiuYanBanT { public class SqlHelper

Action Filters for ASP.NET MVC

本文主要介绍ASP.NET MVC中的Action Filters,并通过举例来呈现其实际应用. Action Filters 可以作为一个应用,作用到controller action (或整个controller action中),以改变action的行为. ASP.NET MVC Framework支持四种不同类型的Filter: Authorization filters – 实现IAuthorizationFilter接口的属性. Action filters – 实现IActionF