接口調用失敗,失敗原因:在 ServiceModel 客戶端配置部分中,找不到引用協定的默認終結點元素

我的程序中,已經配置了webserivce了,但是無法再開發環境使用,我想拿到測試環境使用,而webservice又只能在開發環境調用。這個時候,爲了解決這種尷尬問題,我只能先將就着用開發時的webservice。


在我的web.config中,有如下終結點配置,但是我的程序可能,我希望能在測試環境中,能夠根據web.config中的配置來使用。

<system.serviceModel>
    <client>
      <endpoint address="http://192.168.254.120:7001/ui/services/OnlineBussService"
        binding="basicHttpBinding" bindingConfiguration="OnlineBussServiceSoapBinding"
        contract="ABCLifeFTP.OnlineBussWebService" name="OnlineBussService" />
    </client> 

  </system.serviceModel>

原先開發環境的調用webservice已經寫好了,但是現在不得不爲了動態使用配置而新增代碼,添加了如下的代碼:


 //獲取web.config中的終結點配置

public string GetEndPointAddressByName(string name)   

        {
            string configUrl = "";
            ClientSection clientSection = (ClientSection)WebConfigurationManager.GetSection("system.serviceModel/client");  //找到終結點標籤
            if (clientSection == null && clientSection.Endpoints.Count <= 0)  //判斷是否存在
            {
                RecordLog<string>("Recive:[GetEndPointAddressByName]", "Endpoint地址未配置");
                return null;
            }
            foreach (ChannelEndpointElement cee in clientSection.Endpoints)    //循環終結點,找到需要使用的配置
            {
                if (cee.Name == name && cee.Address != null)
                {
                    configUrl = clientSection.Endpoints[0].Address.AbsoluteUri;   //獲取地址
                    RecordLog<string>("Recive:[GetEndPointAddressByName.configUrl]", configUrl);
                    return configUrl;
                }
            }
            RecordLog<string>("Recive:[GetEndPointAddressByName]", "Endpoint地址未配置或配置錯誤,調用的終端節點名稱:" + name);
            return null;

        }


而在調用web.config代碼中,也需要做修改:


           OnlineBussWebServiceClient OBWSC = null;     //定義接口Client


            try
            {
                string str = GetEndPointAddressByName("OnlineBussService");     //根據此名稱,調用上面的方法,獲取webservice的地址
                if (str != null)
                    OBWSC = new OnlineBussWebServiceClient(new BasicHttpBinding(), new EndpointAddress(str));   //根據地址去實例化接口
                else
                    return;
                if (OBWSC == null)
                {
                    RecordLog<string>("Recive:[SendPolicyInfo.OBWSC]", "服務調用失敗");
                    return;
                }
                RecordLog<OnlineBussWebServiceClient>("Recive:[SendPolicyInfo.OBWSC]", OBWSC);
            }
            catch (Exception ex)
            {
                RecordLog<string>("Recive:[SendPolicyInfo.Exception1]", ex.Message);
                return;
            }

使用接口方法:

        string sss=OBWSC .GetName("Test");


就這樣,我的程序,就可以根據web.config文件中配置的地址,來動態使用接口了,在測試環境使用就不成問題了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章