Coockie less URLs to access WCF services in Silverlight

Thursday 14 May 2015

Coockie less URLs to access WCF services in Silverlight

When you are using silverlight application With Wcf Service then for coockie less url it give some error due to :

    The VS Development Server port changed
    You deployed your application on IIS for testing.
    You deployed your application on any other computer.

For example, http://localhost:5875/applicationname/(S(ccc1a03c1rgapi0mt3kbvo41)) value with in this first backets will change every time so dynamic binding is required
Now there are two apparent choices:

 1:   Modify the URL in ServiceReferences.ClientConfig file
 2:   Use “relative” URLs instead of directly instantiating the service client.

The first solution is to modify ServiceReferences.ClientConfig file and correct the URL of the service. However, this is difficult once the application is deployed since the config file is contained inside the .xap file. I will present the second solution here.

Replace you service client instantiation (the following code):

   
ServiceClient svc=new ServiceClient(); //ServiceClient is the name of service reference

with a method call GetClient() as:
   
ServiceClient svc = GetClient();

And define GetClient() as:

   
private ServiceClient GetClient()
{
  Binding binding = new System.ServiceModel.BasicHttpBinding();
  EndpointAddress endpoint = new EndpointAddress(
    new Uri(Application.Current.Host.Source, "../MyService.svc")); //Application.Current.Host.Source=http://localhost:5875/applicationname/(S(ccc1a03c1rgapi0mt3kbvo41))/ClientBin
  MyClient service = new MyClient(binding, endpoint);
  return service;
}

The above code dynamically builds the service URL from application path. It is a good practice to have service initialization code in one place and you can also control certain other settings (e.g. max buffer size, timeout settings) for your service in that method.

If you need to use the configurations from ServiceReferences.ClientConfig file and modify just the url, you may use another overload that takes the configuration name as parameter:

   
private MyServiceClient GetMyServiceClient()
{
  EndpointAddress endpoint = new EndpointAddress(
    new Uri(Application.Current.Host.Source, "../MyService.svc"));
  MyServiceClient service = new MyServiceClient("CustomBinding_Service", endpoint);
// CustomBinding_Service is the binding name in the client config .but in my case using config is not  //working Properly.
  return service;