简体   繁体   中英

Read WCF service endpoint address by name from web.config

Here I am trying to read my service endpoint address by name from web.config

ClientSection clientSection = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");
var el = clientSection.Endpoints("SecService"); // I don't want to use index here as more endpoints may get added and its order may change
string addr = el.Address.ToString();

Is there a way I can read end point address based on name?

Here is my web.config file

<system.serviceModel>
 <client>
     <endpoint address="https://....................../FirstService.svc" binding="wsHttpBinding" bindingConfiguration="1ServiceBinding" contract="abc.firstContractName" behaviorConfiguration="FirstServiceBehavior" name="FirstService" />
     <endpoint address="https://....................../SecService.svc" binding="wsHttpBinding" bindingConfiguration="2ServiceBinding" contract="abc.secContractName" behaviorConfiguration="SecServiceBehavior" name="SecService" />
     <endpoint address="https://....................../ThirdService.svc" binding="wsHttpBinding" bindingConfiguration="3ServiceBinding" contract="abc.3rdContractName" behaviorConfiguration="ThirdServiceBehavior" name="ThirdService" />
            </client>
    </system.serviceModel>

This will work clientSection.Endpoints[0]; , but I am looking for a way to retrieve by name.

Ie something like clientSection.Endpoints["SecService"] , but it's not working.

This is how I did it using Linq and C# 6.

First get the client section:

var client = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

Then get the endpoint that's equal to endpointName:

var qasEndpoint = client.Endpoints.Cast<ChannelEndpointElement>()
    .SingleOrDefault(endpoint => endpoint.Name == endpointName);

Then get the url from the endpoint:

var endpointUrl = qasEndpoint?.Address.AbsoluteUri;

You can also get the endpoint name from the endpoint interface by using:

var endpointName = typeof (EndpointInterface).ToString();

I guess you have to actually iterate through the endpoints:

string address;
for (int i = 0; i < clientSection.Endpoints.Count; i++)
{
    if (clientSection.Endpoints[i].Name == "SecService")
        address = clientSection.Endpoints[i].Address.ToString();
}

Well, each client-side endpoint has a name - just instantiate your client proxy using that name :

ThirdServiceClient client = new ThirdServiceClient("ThirdService");

Doing this will read the right information from the config file automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM