What is the difference between the process of consuming WCF in Windows app and in Silverlight?
I have a WCF function, "string GetDetails(int x,int y)", and it is deployed on a server now in a Windows application. I can call its function by writing
ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient(); string data = objService.GetData(10,开发者_如何转开发23);
But in Silverlight I am unable to do this. Why?
Because SL only allows asynchronous calls from a service client (it doesn't necessarily mean your operations are asynchronous on the server though).
You'll have to do something like:
ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient();
objService.GetDataCompleted += OnGetDataCompleted;
objService.GetData(10,23);
private void OnGetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
if (e.Error == null)
{
string data = e.Result;
// Do something with data
}
}
You might also want to read up on ClientAccessPolicy.xml. Here is a good link here on SO. In a nutshell, your service must allow itself to be called by granting the Silverlight client access to its domain via the ClientAccessPolicy.xml file. This is often done by creating a Service (that can be implemented in the same project that is hosting your service) that ensures that the ClientAccessPolicy.xml file is available in the correct location.
If your service is self-hosted, you can add code like this to your service startup (Main):
// This service is used to retrieve the client access policy to allow for cross-domain service calls.
ServiceHost ClientAccessPolicyService = null;
ClientAccessPolicyService = new ServiceHost(typeof(ClientAccessPolicyService));
ClientAccessPolicyService.Open();
Lines like this (from our project that is currently in development, I'm sure that these settings will be improved by the time we deploy) are added to your service's app.config file:
<service name="ClientAccessPolicyService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8731/"/>
</baseAddresses>
</host>
<endpoint address=""
binding="webHttpBinding"
contract="IClientAccessPolicy"
behaviorConfiguration="HttpEnableBehavior">
</endpoint>
</service>
<endpointBehaviors>
<behavior name="HttpEnableBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
Where ClientAccessPolicyService is your service that provides the ClientAccessPolicy.xml file and IClientAccessPolicy is the OperationContract.
Hopefully, between this information and the information at the link above (and its embedded links) you be able to get access to your service from Silverlight. There may be more that I am leaving out, but I am really just getting started myself with WCF and Silverlight, so I feel fortunate to have something running!
Good luck!
精彩评论