1. 程式人生 > >一般處理程式的呼叫

一般處理程式的呼叫

在一般處理程式定義多個方法,通過ajax呼叫指定的方法

public class Handler1 : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        //獲取要呼叫的方法
        string action = context.Request["action"].ToString();

        System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(action);
        if (methodInfo != null)
        {
            //在這裡呼叫請求的action
            methodInfo.Invoke(this, new object[] { context });
        }  
    }
    public void GetList(HttpContext context)
    {
       
        context.Response.Write("returns jsonData"); 
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
Js
<script type="text/javascript">
    $.ajax({
        url: "Handler1.ashx",
        type: "Post",        
        data: "action=GetList",//請求Handler1.ashx下面的GetList方法
        success: function (data) {
            alert(data);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }
    });


</script>


優化方案

一般處理程式Base

public class HandlerBase : IHttpHandler
{
    protected HttpContext Context { get; set; }
    protected HttpRequest Request { get; set; }
    protected HttpResponse Response { get; set; }

    public virtual void ProcessRequest(HttpContext context)
    {
        Context = context;
        Request = context.Request;
        Response = context.Response;
        //獲取要呼叫的方法
        string action = context.Request["action"].ToString();
        System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(action);
        if (methodInfo != null)
        {
            //在這裡呼叫請求的action
            //methodInfo.Invoke(this, new object[] { context });
            methodInfo.Invoke(this, new object[] { });
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
一般處理程式Handler1.ashx
public class Handler1 : HandlerBase
{
    public void GetList()
    {
        var name = Request.Form["name"];
        Response.Write("returns jsonData");
    }

}
客戶端
<script type="text/javascript">
    $.ajax({
        url: "Handler1.ashx",
        type: "Post",        
        data: "action=GetList&name=lily",//請求Handler1.ashx下面的GetList方法
        success: function (data) {
            alert(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }
    });

</script>