WCF新手问:从JavaScript调用的方法 [英] WCF Newbie Question: Calling Methods from JavaScript
问题描述
您好!
我是新来的WCF,我认为这将是类似于ASP.NET Web服务,但我无法调用从客户端JavaScript的方法。我的网页形式如下:
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();
}
}
下面是其实现:
namespace Test
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void DoWork()
{
}
public string SayHi()
{
return "Hello, World!";
}
}
}
和最后的JavaScript:
And finally the JavaScript:
function test() {
Test.MyService.SayHi(SayHiSuccess, SayHiError);
}
function SayHiSuccess(result) {
alert(result[0]);
}
function SayHiError(error) {
alert(error.toString());
}
看来,该服务的的sayHi()方法从不执行,虽然我不知道为什么或如何被排除故障。有什么建议?
It appears that the service's SayHi() method never executes, although I'm not sure why or how to being troubleshooting. Any suggestions?
推荐答案
您没有张贴你的web.config的内容。您正在使用什么约束力?你或许应该使用 的WebHttpBinding
。
You didn't post your web.config contents. What binding are you using? You should probably be using webHttpBinding
.
此外,它可以帮助了解您的.svc文件的内容。虽然我从来没有尝试过,我知道你没有,如果你使用<一个在所有修改的web.config href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.webscriptservicehostfactory.aspx\"相对=nofollow> WebScriptServiceHostFactory
为您服务主机工厂。这是简单,只要修改您的.svc文件如下:
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:
- Calling WCF Service from Javascript
- Create a Simple WCF Web...
这篇关于WCF新手问:从JavaScript调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!