views:

29

answers:

1

Hello,

I have a web service that uses WCF. This web service has a single method that I want to be accessible from two different types of clients. The first type of client is a Silverlight application. The second type of client is a AJAX application that relies on JQuery. Is it possible to write the method once such that both types of clients can access the web service? If so, how? Here is my code thus far:

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class myService
{
    [OperationContract]
    public List<string> SearchByName(string name)
    {
        List<string> results = new List<string>();
        results.Add("Bill");
        results.Add("John");
        // more retrieved through database hit.
        return results;
    }
}

Thank you!

+1  A: 

If I were you I would use two distinct interfaces - one for Silverlight (Traditional WS communications), and one for jQuery/JSON.

The service class (myService in your case) would then implement both interfaces. Example:

[ServiceContract(Namespace="urn:Cheeso.Samples" )]
public interface IJsonService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
               RequestFormat=WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json,
               UriTemplate = "search/{name}")]
    List<String> JsonSearchByName(String name);
}

[ServiceContract(Namespace="urn:Cheeso.Samples" )]
public interface IWsService
{
    [OperationContract(Name="SearchByName")]
    List<String> WsSearchByName(String name);
}


[ServiceBehavior(Name="MultiFacedService",  
                 Namespace="urn:Cheeso.Samples")]
public class myService : IJsonService, IWsService
{
    public List<String> JsonSearchByName(String name) 
        { return SearchByName_Impl(name); }
    public List<String> WsSearchByName(String name)
        { return SearchByName_Impl(name); }
    public List<String> SearchByName_Impl(String name)
    { 
       var results = List<string>(); 
       // fill results here...
       return results; 
    }        
}

I see you haven't specified an explicit C# interface to hold the remotely-accessible methods. Consider doing that, as I've shown in the above code. It helps as your WCF designs get more complex.


It's possible to write just one set of methods, and then use a custom ServiceHost to exposes the interface as both Json and WS (See example). But it may be more work than it is worth to take this approach, and the result may be less maintainable.

Cheeso
Is there anything that needs to be added to the web.config? I still cannot get it to work.