如何使用jQuery或简单的js调用简单的WCF服务

Ade*_*eem 5 javascript wcf jquery

我有一个非常简单的hello world WCF服务,如下所示.当我通过添加Web服务引用通过asp.net项目调用它时,它工作得很好.但是当我使用jQuery或标准js ajax调用(使用XMLHttpRequest)调用它时,它会调用success函数但返回null数据.

当我尝试使用此地址通过firefox浏览器访问它时: http://localhost:8282/Test/TestService.svc/HelloWorld

它返回错误,代码为"a:ActionNotSupported",错误详情为

由于EndpointDispatcher上的ContractFilter不匹配,无法在接收方处理带有Action''的消息.这可能是由于合同不匹配(发送方与接收方之间的操作不匹配)或发送方与接收方之间的绑定/安全性不匹配.检查发送方和接收方是否具有相同的合同和相同的绑定(包括安全要求,例如消息,传输,无).

如果我更改绑定,wsHttpBinding那么即使在Firefox中也没有返回任何内容.

这是代码:

文件"Test/ITestService.svc":

[ServiceContract(Namespace = "http://localhost:8282/")]
public interface ITestService
{

    [OperationContract]
    string HelloWorld();
}
Run Code Online (Sandbox Code Playgroud)

文件"Test/TestService.svc":

public class TestService : ITestService
{
    public string HelloWorld()
    {
        return "This is echo from server. Hello World";
    }
}
Run Code Online (Sandbox Code Playgroud)

文件"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>
Run Code Online (Sandbox Code Playgroud)

Ade*_*eem 5

使用上面的代码服务只允许soap请求,以便允许获取http请求,我们必须修改代码,如下所示:

在界面中:

    [WebGet(UriTemplate="helloworld")]
    [OperationContract]
    string HelloWorld();
Run Code Online (Sandbox Code Playgroud)

在web配置中:

  • 添加行为配置:

    <endpoint address="" binding="webHttpBinding" contract="radMLRPC.Test.ITestService" behaviorConfiguration="webBehav">
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后在行为中添加以下标记:

    <endpointBehaviors> <behavior name ="webBehav"> <webHttp /> </ behavior> </ endpointBehaviors>

"请从上面删除多余的空格.它没有显示标签没有额外的空格"


查看一些资源:

使用WCF的RESTful服务简介http://msdn.microsoft.com/en-us/magazine/dd315413.aspx

Endpoint.TV截屏:

对于WCF和WCF REST来说,Endpoint.TV一般都有很好的覆盖范围.http://channel9.msdn.com/shows/Endpoint/