views:

215

answers:

2

Greetings!

I'm new to WCF and I thought it would be similar to ASP.NET web services, but I'm unable to call a method from client-side JavaScript. My web form looks like this:

<form id="form1" runat="server">
   <div>
      <asp:ScriptManager ID="ScriptManager1" runat="server">
         <Scripts>
            <asp:ScriptReference Path="~/test.js" />
         </Scripts>
         <Services>
            <asp:ServiceReference Path="~/MyService.svc" />
         </Services>
      </asp:ScriptManager>
   </div>
   <button onclick="test()">Click Me</button>
</form>

My service's interface looks like this:

namespace Test
{
    [ServiceContract(Namespace = "Test")]
    public interface IMyService
    {
        [OperationContract]
        void DoWork();

        [OperationContract]
        string SayHi();
    }
}

And here's its implementation:

namespace Test
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyService : IMyService
    {
        public void DoWork()
        {
        }

        public string SayHi()
        {
            return "Hello, World!";
        }
    }
}

And finally the JavaScript:

function test() {
    Test.MyService.SayHi(SayHiSuccess, SayHiError);
}

function SayHiSuccess(result) {
    alert(result[0]);
}

function SayHiError(error) {
    alert(error.toString());
}

It appears that the service's SayHi() method never executes, although I'm not sure why or how to being troubleshooting. Any suggestions?

A: 

Your code looks OK. Should be working by right. You could try adding the WebService and the WebMethod attributes as well.

For debugging a WCF web service I normally use Fiddler to track HTTP calls while running the WCF code with a debugger attached (run in Visual Studio in most cases).

fung
+2  A: 

You didn't post your web.config contents. What binding are you using? You should probably be using webHttpBinding.

Also, it may help to know your .svc file contents. Although I've never tried it, I understand that you don't have to modify web.config at all if you use WebScriptServiceHostFactory as your service host factory. That's as simple as modifying your .svc file as follows:

<%@ ServiceHost Service="MyService"
    Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
 %>

If all else fails, here are some resources for you:

Randolpho