1. 程式人生 > >asp.net 動態呼叫webservice方法

asp.net 動態呼叫webservice方法

假設我們現在已經有一個做好的webservice方法:

 [WebMethod(Description = "獲取分包商進場計劃資訊明細(根據時間範圍)")]
        public string getSubcontractorPlanList(string SubcontractorAccount,string  StartDate, string EndDate)
        {
            string returnString = "abc";
            return returnString;
        }

那麼我們如何來呼叫這個方法呢,有兩種方式,一種是通過c#後臺呼叫,一種是通過jquery的ajax方式呼叫。以下是具體的呼叫方法:

① 建立一個呼叫webservice的代理類:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;


namespace WebApplication1
{
    public class WebServiceAgent
{
private object agent; private Type agentType; private const string CODE_NAMESPACE = "Beyondbit.WebServiceAgent.Dynamic"; /// <summary< /// 建構函式 /// </summary< /// <param name="url"<</param< public WebServiceAgent() { string
url = "http://xx.com/AppService/abc.asmx"; XmlTextReader reader = new XmlTextReader(url + "?wsdl"); //建立和格式化 WSDL 文件 ServiceDescription sd = ServiceDescription.Read(reader); //建立客戶端代理代理類 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, null, null); //使用 CodeDom 編譯客戶端代理類 CodeNamespace cn = new CodeNamespace(CODE_NAMESPACE); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu); agentType = cr.CompiledAssembly.GetTypes()[0]; agent = Activator.CreateInstance(agentType); } ///<summary< ///呼叫指定的方法 ///</summary< ///<param name="methodName"<方法名,大小寫敏感</param< ///<param name="args"<引數,按照引數順序賦值</param< ///<returns<Web服務的返回值</returns> public object Invoke(string methodName, params object[] args) { MethodInfo mi = agentType.GetMethod(methodName); return this.Invoke(mi, args); } ///<summary< ///呼叫指定方法 ///</summary< ///<param name="method"<方法資訊</param< ///<param name="args"<引數,按照引數順序賦值</param< ///<returns<Web服務的返回值</returns< public object Invoke(MethodInfo method, params object[] args) { return method.Invoke(agent, args); } public MethodInfo[] Methods { get { return agentType.GetMethods(); } } } }

②,建立一個呼叫webservice 的頁面:GetWebServiceFunc.aspx
,在其後臺程式碼中,增加一個方法:

[WebMethod]
        public static string Invoke(string MethodName,string ObjStr)
        {

            object[] args = null;
            string[] arr = ObjStr.Split(new string[] { ";#" }, StringSplitOptions.None);

            if (arr != null && arr.Length > 0)
            {
                args = new object[arr.Length-1];
                for (int i = 0; i < arr.Length-1; i++)
                {
                    string value = Convert.ToString(arr[i]);
                    if (value == "null")
                    {
                        args[i] = "";
                    }
                    else
                    {
                        args[i] = value;
                    }
                }
            }
            return Convert.ToString(new WebServiceAgent().Invoke(MethodName, args));
        }

接下來,我們就可以通過以下方式,來呼叫這個方法了,第一種是通過c#後端程式來呼叫。

WebServiceAgent agent = new WebServiceAgent();
            object[] args = new object[3];
            args[0] = "csfbs";
            args[1] = "2017-07-01";
            args[2] = "";
            string text = agent.Invoke("getSubcontractorPlanList", args).ToString();

另一種,是通過jquery的ajax來呼叫:

<script src="./js/jquery-1.9.1.min.js"></script>
   <script>
       $(document).ready(function () {
           $.ajax({
               type: "Post",
               //方法所在頁面和方法名                     
               url: "GetWebServiceFunc.aspx/Invoke",
               data: "{'MethodName':'getSubcontractorPlanList','ObjStr':'csfbs;#2017-07-01;#null;#'}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",

               success: function (data) {
                   //返回的資料用data.d獲取內容                          
                   alert(data.d);
               },
               error: function (err) {
                   alert('fail');
               }
           });

       });
   </script>

通過以上程式,我們就實現了對webservice的呼叫,在這裡順便記錄了具體的使用方法。