asp.net web form中 用attribute实现权限验证方式
以前项目的代码比较陈旧,今天抽空优化了一下.作为记录.
以前每次请求一个方法都要验证是否登录 if xxx等 现在通过global文件中的改进 反射这个方法的属性是否需要权限
要的话先验证权限.以下代码 只提供思路和演示.
如何使用
global中的写法是
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current != null) { byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length]; HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length); string req = System.Text.Encoding.Default.GetString(byts); req = HttpContext.Current.Server.UrlDecode(req); if (!string.IsNullOrEmpty(req)) { req = req.Replace("data=", ""); var ajaxModel = Utils.JsonHelper.FromJson<AjaxRequestModel>(req);//把请求的流转换为json string methodName = ajaxModel.MethodAlias; var className = AjaxCache.GetClassName(methodName); string assemblyName = "Test.Module"; if (!String.IsNullOrEmpty(assemblyName) && !String.IsNullOrEmpty(className)) { Assembly assembly = GetAssembly(assemblyName);//我这里用的缓存来实现资源加载的不然每次都需要反射 Type type = assembly.GetType(className, true, true); if (type != null) { MethodInfo[] methodInfos = type.GetMethods(); foreach (MethodInfo mi in methodInfos) { System.Attribute[] attrs = System.Attribute.GetCustomAttributes(mi); //反射获得用户自定义属性 foreach (System.Attribute attr in attrs) { if (attr is CheckLoginAttribute) { CheckLoginAttribute a = (CheckLoginAttribute)attr; System.Console.WriteLine("过了没? ", a.IsLogin);//这里也可以处理 也可以不处理. } } } } } } } }
/// <summary> /// 反射资源缓存调用 /// </summary> /// <param name="assemblyName"></param> /// <returns></returns> private static Assembly GetAssembly(string assemblyName) { object assemblyObject = CacheHelper.GetCache(assemblyName);//这里可以用 iis缓存来实现 if (assemblyObject == null) { Assembly assembly = null; assembly = Assembly.Load(assemblyName); CacheHelper.SetCache(assemblyName, assembly, DateTime.Now.AddMinutes(60)); return assembly; } else { return (Assembly)assemblyObject; } }
[AttributeUsage(AttributeTargets.Method,AllowMultiple=false, Inherited=true )] public class CheckLoginAttribute : Attribute { /// <summary> /// 检测是否登录 /// </summary> public bool IsLogin { get; set; } public CheckLoginAttribute( ) { try { if (1==1) { IsLogin = true; //throw new Exception("登录错啦"); //var model = new ResponseInfo { State = ResultState.Failed, ErrorMessage = "您未登录,请登录!" }; //HttpContext.Current.Response.Write(JsonConvert.SerializeObject(model)); //HttpContext.Current.Response.End(); } else { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write("{State:1,Msg='未登录'}"); HttpContext.Current.Response.End(); } } catch (Exception ex) { LogHelper.WriteExceptionLog("CheckLoginAttribute", ex); throw; } } }