以前在使用Jquery的AJax的時候,總是要新建一個ashx或者ASPx來處理程序,當大量使用AJax的時候,發現建了一大堆的處理頁面,剛覺很是不爽
後來我想,用反射的方式直接去掉cs裡的方法不是很好,很爽,這就是初衷。
1,先寫個處理程序
public class Handler : IHttpHandler, IRequiresSessionState
2,核心代碼
string method = Request["METHAD"];//namespace.class.method//包名.類名.方法名string ClassNamespace = method.Substring(0, method.LastIndexOf("."));// "</SPAN>< style="FONT-FAMILY: 宋體; COLOR: green; FONT-SIZE: 9pt" SPAN >?;< SPAN>object objType = CreateObjectNoCache(Request["DLL"], ClassNamespace);//反射Type ht = objType.GetType();
List<string> likey = new List<string>();
foreach (string item in Request.Params.AllKeys)
{
if (item.StartsWith("[__DOTNET__]"))
likey.Add(item);
}
int length = likey.Count;//Request.Form.AllKeys.Length;
//int length=Request
//反射方法參數,和類型object[] obj = new object[length];// 數據Type[] objTypes = new Type[length];//類型for (int i = 0; i < length; i++)
{
string ReqKey = likey[i].Substring(12);//Request.Form.AllKeys[i]; Type tType = null;
if (ReqKey.IndexOf("[") != -1)
{
tType = Type.GetType(ReqKey.Remove(ReqKey.LastIndexOf("[")), true, true);
}
else {
tType = Type.GetType(ReqKey, true, true);
}
objTypes[i] = tType;//類型賦值
//如果它是值類型,或者String if (tType.Equals(typeof(string)) || tType.Equals(typeof(string[])) || (!tType.IsInterface && !tType.IsClass))
{
obj[i] = Convert.ChangeType(Request.Params[likey[i]], tType);
}
else if (tType.IsClass)//如果是類,將它的JSon字符串轉換成對象 {
obj[i] = JavaScriptConvert.DeserializeObject(Request.Params[likey[i]], tType); //Serialize.Deserialize(Request.Form[i], tType); }
}
//TODOMethodInfo methodInfo = ht.GetMethod(method.Substring(method.LastIndexOf(".") + 1), objTypes);
object returnValue = null;
foreach (object attribute in methodInfo.GetCustomAttributes(true))
{
if (attribute is AJaxMethod)
{
returnValue = methodInfo.Invoke(objType, obj);
break;
}
}
//執行方法
//object returnValue = methodInfo.Invoke(objType, obj);if (returnValue == null)
throw new Exception("你沒用權限執行該方法,是否加了[XAJaxMethod]自定義屬性");
3,返回值處理,類會直接被序列化成JSon格式
#region 處理返回值
if (returnValue.GetType().IsClass && !returnValue.GetType().Equals(typeof(string)))
{
if (returnValue.GetType().Equals(typeof(XMLDocument)))
{
//如果是XML文檔,則寫入XML文檔
Response.ContentType = "text/XML";
Response.Write(((XmlDocument)returnValue).OuterXML);
}
else if (returnValue.GetType().IsClass && returnValue.GetType().Equals(typeof(DataTable)))
{
if (!string.IsNullOrEmpty(Request["callback"]) && Request["callback"].StartsWith("JSonp"))
{
Response.ContentType = "application/JSon";
Response.ContentEncoding = Encoding.Default;
Response.Write(Request["callback"] + "(" + Json.DataTableToJSon("Rows", (DataTable)returnValue) + ")");
}
else
Response.Write(Json.DataTableToJSon("Rows", (DataTable)returnValue));
}
else
{
if (!string.IsNullOrEmpty(Request["callback"]) && Request["callback"].StartsWith("JSonp"))
{
Response.ContentType = "application/JSon";
Response.ContentEncoding = Encoding.Default;
Response.Write(Request["callback"] + "(" + JavaScriptConvert.SerializeObject(returnValue) + ")");
}
else
Response.Write(JavaScriptConvert.SerializeObject(returnValue));
}
}
else
{
if (!string.IsNullOrEmpty(Request["callback"]) && Request["callback"].StartsWith("JSonp"))
{
Response.ContentType = "application/JSon";
Response.ContentEncoding = Encoding.Default;
Response.Write(Request["callback"] + "(\"" + returnValue.ToString() + "\")");
}
else
Response.Write(returnValue.ToString());
}
#endregion
4,為了防止跨權限調用了其他的方法加了個自定義屬性
public class AJaxMethod : Attribute
{
public override string ToString()
{
return "XAJaxMethod";
}
}
5,webconfig配置
<httpHandlers> <add path="DotNet2.ashx" verb="*" type="AjaxHandler.Handler,AJaxHandler"/></httpHandlers>
6,jquery調用
$.AJax({
url: "/DotNet2.ashx?METHAD=AjaxTest._Default.Test&DLL=AJaxTest",
data: {
"[__DOTNET__]System.String": "測試測試一"
},
success: function(JSon) {
alert(JSon);
}
});
7,url格式
METHAD:命名空間.類名.方法名
DLL:DLL名稱
8,AJax參數
data: {
"[__DOTNET__]System.String": "測試測試二",
"[__DOTNET__]System.Int32": "12345678"
}
需要加上[__DOTNET__]前綴,後面是參數類型,前綴是為了處理get方式9,下載源代碼