jQuery Ajax调用WCF服务返回“Method not allowed(405)”

时间:2010-06-16 20:57:31

标签: c# jquery ajax wcf json

我使用VS 2008创建了一个WCF SOAP服务,它服务于服务器端。我在下面的代码中使用jQuery / json(没有ASP.NET scriptmanager)来调用相同的服务/合同客户端。当我将服务URL放入浏览器时,我得到了正确的服务页面,当我从javascript调用服务并通过Firebug跟踪时,我得到“405方法不允许”。

ajax()错误函数的statusText和responseText不包含任何内容,并且由于某些奇怪的原因错误函数被调用两次。我也是从https页面调用该服务。

相同的ajax代码可以与服务器端和客户端类似的传统Web服务一起使用,也可以使用页面方法。

任何线索?我还注意到我没有安装Windows Communication Foundation HTTP激活和非HTTP激活。我需要这些吗?我的服务器端WCF服务可以工作。

接口:

[ServiceContract]
public interface ICust
{
    [OperationContract]
    [WebInvoke(Method = "POST", 
        BodyStyle = WebMessageBodyStyle.Wrapped, 
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    bool GetCust(string zzz);
}

类别:

public class Cust: ICust
{
    public bool GetCust(string zzz)
    {
        // Do Stuff
        // Return true/false; 
    }
 }

的web.config:

<behaviors>
    <serviceBehaviors>
        <behavior name="E.W.CustomerBehavior" >
            <serviceMetadata httpGetEnabled="true" />
        </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
        <behavior name="webCallable">
            <webHttp />
        </behavior>            
    </endpointBehaviors>
</behaviors>

<services>
    <service behaviorConfiguration="E.W.CustomerBehavior"
        name="E.W.Customer">
        <endpoint address="http://zzzz/Cust.svc" 
            binding="webHttpBinding" 
            contract="E.W.ICust" 
            behaviorConfiguration="webCallable">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
        <endpoint address="mex" 
            binding="mexHttpBinding" 
            contract="IMetadataExchange" />
    </service>
</services>

jQuery的:

$.ajax({
    cache: false,
    async: false,
    type: "POST",
    url: "http://zzzz/Cust.svc/GetCust",
    contentType: "application/json",
    dataType: "json",
    data: "{'zzz': '" + $("#ctl00_zz_zzz").val() + "'}",
    success: function(msg) {
        // do stuff
    },
    error: function(z) { alert(z.responseText); }
});

2 个答案:

答案 0 :(得分:2)

尝试在类Cust

上添加以下属性
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

答案 1 :(得分:0)

问题是https。调用服务的页面是https,因此“方法不允许”。

我更改了web.config和javascript文件以使用https调用服务,但它运行良好。

This帮助了我。

现在我看到人们为什么说WCF在前面工作更多。

我安装了Windows Communication Foundation HTTP激活和非HTTP激活,这与我的问题无关,但我仍然不清楚它们是什么。