介面呼叫失敗,失敗原因:在 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檔案中配置的地址,來動態使用介面了,在測試環境使用就不成問題了。