1.前段JS代码
//"UserAcess":指定的类,"CheckLogin":指定的方法, //objparam:要传的参数,"function(response, options)":callback AjaxHandle("UserAcess", "CheckLogin", objparam, function(response, options) {});
2请求跑到ajaxhandle.ashx文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using ShippingManager.Command; using System.Web.SessionState; using NoxTimer.Net.Apis; using System.Text; namespace ShippingManager { /// <summary> /// Summary description for $codebehindclassname$ /// </summary> [WebService(Namespace = "zybajaxHandle")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class AjaxHandler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { string classname = context.Request.QueryString["classname"];//接收传入的类名 string method = context.Request.QueryString["method"];//接收传入的方法 if (!string.IsNullOrEmpty(classname) && !string.IsNullOrEmpty(method)) { AjaxResult result = null; try { PreInitPage(); RequstHandle handle = new RequstHandle(); result = handle.Handle(classname, method, context); } catch (Exception ex) { result = new AjaxResult(); result.Success = false; result.Message = ex.Message; result.data = null; } context.Response.ContentType = "text/plain"; context.Response.Write(result.ToJson()); context.Response.End(); } else { context.Response.ContentType = "text/html"; context.Response.Write("找不到匹配方法"); context.Response.End(); } } public bool IsReusable { get { return false; } } private void PreInitPage() { if (!String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["CopyRight"])) { return; } AjaxResult resu = new EasyAjaxResult(); long[] keyHandles; long keyNum = 0; uint appID = 0xffffffff; long nRet = NoxTimerAppApis.NoxFind(appID, out keyHandles, ref keyNum); if (nRet != 0) { resu.Success = false; resu.Message = "Error:" + NoxTimerAppApis.NoxGetLastError().ToString(); HttpContext.Current.Response.Write(resu.ToJson()); HttpContext.Current.Response.End(); } String userPin = "79de3607198f9a27"; nRet = NoxTimerAppApis.NoxOpen(keyHandles[0], userPin); if (nRet != 0) { resu.Success = false; resu.Message = "Error:" + NoxTimerAppApis.NoxGetLastError().ToString(); HttpContext.Current.Response.Write(resu.ToJson()); HttpContext.Current.Response.End(); } ////获取硬件序列号 //String sGUID = ""; //nRet = NoxTimerAppApis.NoxGetUID(keyHandles[0], ref sGUID); //if (nRet != 0) //{ // Response.Write("HD No. Error"); //} ////存储区读 //byte[] readStorage = new byte[16]; //if (0 != NoxTimerAppApis.NoxReadStorage(keyHandles[0], readStorage)) { } ////加密锁内存区写(8字节内存区) //byte[] memWData = new byte[8] { 91, 92, 93, 94, 95, 96, 97, 98 }; //int v= new Random().Next(10000000, 99999999); //byte[] memWData = System.Text.Encoding.Default.GetBytes(v.ToString()); //Application.Lock(); //Application["_2345234536"] = v; //Application.UnLock(); //if (0 != NoxTimerAppApis.NoxWriteMem(keyHandles[0], memWData)) { // Response.Write("Error:"+NoxTimerAppApis.NoxGetLastError().ToString ()); //} ////内存区读 //byte[] memRData = new byte[8]; //if (0 != NoxTimerAppApis.NoxReadMem(keyHandles[0], memRData)) //{ // Response.Write("Error:" + NoxTimerAppApis.NoxGetLastError().ToString()); // Response.End(); //} //else //{ // String str = Encoding.Default.GetString(memRData); // if (str.CompareTo(Application["_2345234536"].ToString()) != 0) // { // Response.Write("HAHAHAHAHAHAHA"); // Response.Close(); // } //} ////获取加密锁时间模式、失效时间 //long Mode, endYear, endMonth, endDay, endHour, endMinute; //Mode = 0; //endYear = 0; //endMonth = 0; //endDay = 0; //endHour = 0; //endMinute = 0; //nRet = NoxTimerAppApis.NoxGetExpiryDateTime(keyHandles[0], ref Mode, ref endYear, ref endMonth, ref endDay, ref endHour, ref endMinute); //if (nRet != 0) //{ // return; //} //String msg = String.Format("DateTime Successfuflly! Mode:" + Mode.ToString() + " endTimer:" + endYear.ToString() + "/" // + endMonth.ToString() + "/" // + endDay.ToString() + " " // + endHour.ToString() + ":" // + endMinute.ToString()); //关闭加密锁 NoxTimerAppApis.NoxClose(keyHandles[0]); } } }
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Reflection; using System.Web; using System.Runtime.Remoting; namespace ShippingManager.Command { /* */ public class RequstHandle { /// <summary> /// 将类名和参数指定方法 /// </summary> /// <param name="classname"></param> /// <param name="methodname"></param> /// <param name="context"></param> /// <returns></returns> public AjaxResult Handle(string classname, string methodname,HttpContext context) { AjaxResult result = null; string str = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);//请求的应用程序地址 string path = str + @"bin\ShippingManager.DataAcess.dll"; ObjectHandle ohandle = Activator.CreateInstanceFrom(path, "ShippingManager.DataAcess." + classname); if (ohandle != null) { System.Type t = ohandle.Unwrap().GetType(); if (t != null) { object o = Activator.CreateInstance(t); //跑到指定的类中的方法!!(ajax方法请求+"on"指向方法名) MethodInfo minfo = t.GetMethod("on" + methodname, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); if (minfo != null) { object[] parmas = new object[] { context }; // result = (AjaxResult)minfo.Invoke(o, parmas); } else { result = new AjaxResult(); result.Success = false; result.Message = "找不到匹配方法:" + methodname; } } else { result = new AjaxResult(); result.Success = false; result.Message = "找不到匹配类:" + classname; } } else { result = new AjaxResult(); result.Success = false; result.Message = "找不到ShippingManager.DataAcess.dll"; } return result; } /// <summary> /// 从httpcontext中创建实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <returns></returns> public static T GenerateEntity<T>(HttpContext context) { Type enumType = typeof(T); if (enumType.IsGenericType) { T obj = Activator.CreateInstance<T>(); SetListValue<T>(context, 0, obj); return obj; } else { T obj = Activator.CreateInstance<T>(); PropertyInfo[] pinfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in pinfo) { string str = context.Request[p.Name]; if (!string.IsNullOrEmpty(str)) { p.SetValue(obj, TypeConvert(str, p.PropertyType), null); } } return obj; } } /// <summary> /// 递归创建添加泛型实例,如list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <param name="index"></param> /// <param name="iList"></param> private static void SetListValue<T>(HttpContext context, int index,T iList) { Type[] genericArguments = typeof(T).GetGenericArguments(); if (genericArguments.Length > 0) { System.Type enumType = genericArguments[0]; object obj = Activator.CreateInstance(enumType); PropertyInfo[] pinfo = enumType.GetProperties(BindingFlags.Public | BindingFlags.Instance); bool allisNull = true; foreach (PropertyInfo p in pinfo) { if (context.Request[p.Name + "_" + index.ToString()] != null) { string str = context.Request[p.Name + "_" + index.ToString()]; p.SetValue(obj, TypeConvert(str, p.PropertyType), null); allisNull = false; } } if (allisNull) { return; } MethodInfo addMList = typeof(T).GetMethod("Add"); addMList.Invoke(iList, new object[] { obj }); } SetListValue<T>(context, index + 1, iList); } /// <summary> /// 从httpcontext中创建实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <returns></returns> public static T GenerateListEntity<T>(HttpContext context) { Type enumType = typeof(T); if (enumType.IsGenericType) { T obj = Activator.CreateInstance<T>(); SetListValueWidthTypeName<T>(context, 0, obj); return obj; } else { T obj = Activator.CreateInstance<T>(); PropertyInfo[] pinfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in pinfo) { string str = context.Request[p.Name]; if (!string.IsNullOrEmpty(str)) { p.SetValue(obj, TypeConvert(str, p.PropertyType), null); } } return obj; } } /// <summary> /// 递归创建添加泛型实例,如list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <param name="index"></param> /// <param name="iList"></param> private static void SetListValueWidthTypeName<T>(HttpContext context, int index, T iList) { Type[] genericArguments = typeof(T).GetGenericArguments(); if (genericArguments.Length > 0) { System.Type enumType = genericArguments[0]; object obj = Activator.CreateInstance(enumType); PropertyInfo[] pinfo = enumType.GetProperties(BindingFlags.Public | BindingFlags.Instance); bool allisNull = true; foreach (PropertyInfo p in pinfo) { if (context.Request[enumType.Name + "_" + p.Name + "_" + index.ToString()] != null) { string str = context.Request[enumType.Name + "_" + p.Name + "_" + index.ToString()]; p.SetValue(obj, TypeConvert(str, p.PropertyType), null); allisNull = false; } } if (allisNull) { return; } MethodInfo addMList = typeof(T).GetMethod("Add"); addMList.Invoke(iList, new object[] { obj }); } SetListValueWidthTypeName<T>(context, index + 1, iList); } public static T GenerateEntity<T>(System.Web.UI.ControlCollection controls) { T obj = Activator.CreateInstance<T>(); IEnumerable<System.Web.UI.HtmlControls.HtmlForm> form = controls.OfType<System.Web.UI.HtmlControls.HtmlForm>(); if (form != null && form.Count() > 0) { IEnumerable<System.Web.UI.WebControls.WebControl> allcontrol = form.First().Controls.OfType<System.Web.UI.WebControls.WebControl>(); IEnumerable<System.Web.UI.HtmlControls.HtmlControl> htmlcontrol = form.First().Controls.OfType<System.Web.UI.HtmlControls.HtmlControl>(); PropertyInfo[] pinfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in pinfo) { var contros = allcontrol.Where(item => item.ID.StartsWith("con") && (item.ID.Substring(3) == p.Name) || item.ID.Contains(p.Name)); var htmlcons = htmlcontrol.Where(item => item.ID.StartsWith("con") && (item.ID.Substring(3) == p.Name) || item.ID.Contains(p.Name)); if (contros.Count() > 0) { System.Web.UI.WebControls.WebControl c = contros.First(); SetProperptyValue(p, c, obj); } else if (htmlcons.Count() > 0) { System.Web.UI.HtmlControls.HtmlControl c = htmlcons.First(); SetProperptyValue(p, c, obj); } } } return obj; } private static void SetProperptyValue(PropertyInfo p, System.Web.UI.Control c, object obj) { Type t = c.GetType(); if (t == typeof(System.Web.UI.WebControls.TextBox)) { p.SetValue(obj, TypeConvert(((System.Web.UI.WebControls.TextBox)c).Text.Trim(), p.PropertyType), null); } else if (t == typeof(System.Web.UI.WebControls.DropDownList)) { p.SetValue(obj, TypeConvert(((System.Web.UI.WebControls.DropDownList)c).SelectedValue, p.PropertyType), null); } else if (t == typeof(System.Web.UI.WebControls.RadioButtonList)) { p.SetValue(obj, TypeConvert(((System.Web.UI.WebControls.RadioButtonList)c).SelectedValue, p.PropertyType), null); } else if (t == typeof(System.Web.UI.WebControls.Label)) { p.SetValue(obj, TypeConvert(((System.Web.UI.WebControls.Label)c).Text.Trim(), p.PropertyType), null); } else if (t == typeof(System.Web.UI.WebControls.CheckBox)) { p.SetValue(obj, TypeConvert(((System.Web.UI.WebControls.CheckBox)c).Checked ? "1" : "0", p.PropertyType), null); } else if (t == typeof(System.Web.UI.HtmlControls.HtmlInputHidden)) { p.SetValue(obj, TypeConvert(((System.Web.UI.HtmlControls.HtmlInputHidden)c).Value, p.PropertyType), null); } else if (t == typeof(System.Web.UI.HtmlControls.HtmlInputText)) { p.SetValue(obj, TypeConvert(((System.Web.UI.HtmlControls.HtmlInputText)c).Value.Trim(), p.PropertyType), null); } } public static void SetControlValue(System.Web.UI.ControlCollection controls, object obj) { if (obj != null) { IEnumerable<System.Web.UI.HtmlControls.HtmlForm> form = controls.OfType<System.Web.UI.HtmlControls.HtmlForm>(); if (form != null && form.Count() > 0) { IEnumerable<System.Web.UI.WebControls.WebControl> allcontrol = form.First().Controls.OfType<System.Web.UI.WebControls.WebControl>(); IEnumerable<System.Web.UI.HtmlControls.HtmlControl> htmlcontrol = form.First().Controls.OfType<System.Web.UI.HtmlControls.HtmlControl>(); PropertyInfo[] pinfo = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in pinfo) { IEnumerable<System.Web.UI.WebControls.WebControl> contros; IEnumerable<System.Web.UI.HtmlControls.HtmlControl> htmlcons; if (p.PropertyType.IsEnum) { contros = allcontrol.Where(item => item.ID.StartsWith("con") && (item.ID.Substring(3) == p.Name) || item.ID.Contains(p.Name)); htmlcons = htmlcontrol.Where(item => item.ID.StartsWith("con") && (item.ID.Substring(3) == p.Name) || item.ID.Contains(p.Name)); } else { contros = allcontrol.Where(item => item.ID.StartsWith("con") && item.ID.Substring(3) == p.Name); htmlcons = htmlcontrol.Where(item => item.ID.StartsWith("con") && item.ID.Substring(3) == p.Name); } if (contros.Count() > 0) { System.Web.UI.WebControls.WebControl c = contros.First(); SetCValue(p, c, obj); } else if (htmlcons.Count() > 0) { System.Web.UI.HtmlControls.HtmlControl c = htmlcons.First(); SetCValue(p, c, obj); } } } } } private static void SetCValue(PropertyInfo p, System.Web.UI.Control c, object obj) { Type t = c.GetType(); if (t == typeof(System.Web.UI.WebControls.TextBox)) { ((System.Web.UI.WebControls.TextBox)c).Text=GetPropertyValue(p,obj); } else if (t == typeof(System.Web.UI.WebControls.DropDownList)) { try { string thevalue = GetPropertyValue(p, obj); if (!string.IsNullOrEmpty(thevalue)) { ((System.Web.UI.WebControls.DropDownList)c).SelectedValue = thevalue; } } catch { System.Web.UI.WebControls.DropDownList ddl = ((System.Web.UI.WebControls.DropDownList)c); if (ddl.Items.Count > 0) ddl.SelectedValue = ddl.Items[0].Value; else ddl.SelectedValue = null; } } else if (t == typeof(System.Web.UI.WebControls.Label)) { ((System.Web.UI.WebControls.Label)c).Text = GetPropertyValue(p, obj); } else if (t == typeof(System.Web.UI.WebControls.RadioButtonList)) { ((System.Web.UI.WebControls.RadioButtonList)c).SelectedValue = GetPropertyValue(p, obj); } else if (t == typeof(System.Web.UI.WebControls.CheckBox)) { ((System.Web.UI.WebControls.CheckBox)c).Checked = (bool)TypeConvert(GetPropertyValue(p, obj), typeof(bool)); } else if (t == typeof(System.Web.UI.HtmlControls.HtmlInputHidden)) { ((System.Web.UI.HtmlControls.HtmlInputHidden)c).Value = GetPropertyValue(p, obj); } else if (t == typeof(System.Web.UI.HtmlControls.HtmlInputText)) { ((System.Web.UI.HtmlControls.HtmlInputText)c).Value = GetPropertyValue(p, obj); } } private static string GetPropertyValue(PropertyInfo p, object obj) { object pobj = p.GetValue(obj, null); if (pobj != null) { if (p.PropertyType == typeof(DateTime)) { if (Convert.ToDateTime(pobj).Equals(new DateTime(1900, 1, 1))) { return string.Empty; } } else if (p.PropertyType.IsEnum) { Type enumType = p.PropertyType.UnderlyingSystemType; int i = (int)Enum.Parse(enumType, p.GetValue(obj, null).ToString()); return i.ToString(); } return pobj.ToString(); } else return string.Empty; } public static object TypeConvert(string value, Type type) { Type enumType = type; if (enumType.IsGenericType && (enumType.GetGenericTypeDefinition() == typeof(Nullable<>))) { Type[] genericArguments = enumType.GetGenericArguments(); if (genericArguments.Length > 0) { enumType = genericArguments[0]; } } if (typeof(int) == enumType) { if (value.ToLower() == "true") return 1; else if (value.ToLower() == "false") return 0; else { int temp = 0; int.TryParse(value, out temp); return temp; } } if (typeof(double) == enumType) { double temp = 0.0; double.TryParse(value, out temp); return temp; } if (typeof(decimal) == enumType) { decimal temp = 0; decimal.TryParse(value, out temp); return temp; } if (typeof(bool) == enumType) { return toBool(value); } if (typeof(byte) == enumType) { return Convert.ToByte(value); } if (typeof(char) == enumType) { return Convert.ToChar(value); } if (typeof(DateTime) == enumType) { return toDate(value); } if (typeof(float) == enumType) { float temp = 0f; float.TryParse(value, out temp); return temp; } if (typeof(short) == enumType) { short temp = 0; short.TryParse(value, out temp); return temp; } if (typeof(long) == enumType) { long temp = 0L; long.TryParse(value, out temp); return temp; } if (enumType.IsEnum) { return Enum.Parse(enumType, value); } return value; } private static bool toBool(string boolStr) { if ((string.IsNullOrEmpty(boolStr) || (boolStr.ToLower() == "false")) || (boolStr == "0")) { return false; } return true; } private static DateTime toDate(string dateStr) { if (string.IsNullOrEmpty(dateStr)) { return DateTime.MinValue; } try { return DateTime.Parse(dateStr); } catch { return DateTime.MinValue; } } } }
3.Invoke的使用
现在已处理登录页面的请求为例:
1.Login.aspx
function Login() { var loginame = document.getElementById("txtloginname").value; var pwd = document.getElementById("txtpwd").value; var objparam = { LoginName: loginame, Password: pwd }; // AjaxHandle("UserAcess", "CheckLogin", objparam, function(response, options) { var json = response.responseText; var obj = parseJsonResult(json); if (obj != null && obj.Success) { location.href = 'Main.aspx'; } else { Ext.MessageBox.alert("错误", obj.Message, function(btn) { }); } }); }
2。经过上面介绍发送到ajaxhandle.ashx,经过ajaxresult.cs,使用Invoke 到了要处理的UserAccess.cs
public AjaxResult onCheckLogin(System.Web.HttpContext context) { AjaxResult result = new AjaxResult(); try { //成功登陆的USER对象 Users user = CanLogin(context.Request["LoginName"], context.Request["Password"]); if (user != null) { object obj = System.Web.HttpContext.Current.Cache.Get(user.UserGUID); if (obj == null || obj+""=="") { //记录user对象的登陆时间 TimeSpan SessTimeout = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0,0); System.Web.HttpContext.Current.Cache.Insert(user.UserGUID, user.LoginName, null, DateTime.MaxValue, SessTimeout, System.Web.Caching.CacheItemPriority.NotRemovable, null); result.Success = true; //有啥用呢? UserUtil.CurrentUser = user; result.data = user; } else { result.Success = false; result.Message = "登录错误,用户已经登录!"; } } else { result.Success = false; result.Message = "用户名或密码错误!"; } } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; }