我有一个非常简单的 hello world WCF 服务,如下所示。当我通过添加 Web 服务引用通过 asp.net 项目调用它时,它工作得很好。但是当我使用 jQuery 或标准 js ajax 调用(使用 XMLHttpRequest
)调用它时,它会回调成功函数但返回空数据。
当我尝试使用此地址通过 firefox 浏览器访问它时:http://localhost:8282/Test/TestService.svc/HelloWorld
它返回一个代码为“a:ActionNotSupported”的错误,错误详细信息为
The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).
如果我将绑定(bind)更改为 wsHttpBinding
,那么即使在 Firefox 中它也不会返回任何内容。
代码如下:
文件“测试/ITestService.svc”:
[ServiceContract(Namespace = "http://localhost:8282/")]
public interface ITestService
{
[OperationContract]
string HelloWorld();
}
文件“测试/TestService.svc”:
public class TestService : ITestService
{
public string HelloWorld()
{
return "This is echo from server. Hello World";
}
}
文件“web.config”
<system.serviceModel>
<services>
<service name="radMLRPC.Test.TestService" behaviorConfiguration="radMLRPC.Test.TestServiceBehavior"
<endpoint address="HelloWorld" binding="webHttpBinding" contract="radMLRPC.Test.ITestService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="radMLRPC.Test.TestServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
最佳答案
服务上面的代码只允许 soap 请求,所以要允许 Get http 请求,我们必须修改代码如下:
在界面中:
[WebGet(UriTemplate="helloworld")]
[OperationContract]
string HelloWorld();
在网络配置中:
添加行为配置:
<endpoint address="" binding="webHttpBinding" contract="radMLRPC.Test.ITestService" behaviorConfiguration="webBehav">
然后在behaviors中添加如下标签:
<端点行为> <行为名称="webBehav">
行为>
“请从上面删除多余的空格。它没有显示没有多余空格的标签”
查看一些资源:
WCF RESTful 服务简介 http://msdn.microsoft.com/en-us/magazine/dd315413.aspx
Endpoint.TV 截屏视频:
- 使用 WCF 构建 RESTful 服务(第 1 部分) http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF/
- 使用 WCF 构建 RESTful 服务(第 2 部分) http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF-Part-2/
- 在 WCF 中调用 RESTful 服务 http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Calling-RESTful-Services-in-WCF/
Endpoint.TV 通常对 WCF 和 WCF REST 内容有很好的覆盖。 http://channel9.msdn.com/shows/Endpoint/
关于javascript - 如何使用 jQuery 或简单的 js 调用简单的 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3280124/