WCF Jquery Ajax跨域策略 - “方法不允许”

时间:2012-06-27 12:34:31

标签: jquery wcf cross-domain

我正在尝试使用WCF服务,使用从Localhost到服务器的Jquery,但不断获得“405 Method Not Allowed”。

这是我正在使用的配置:

<system.serviceModel>
<bindings>
  <webHttpBinding>
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
      <binding name="jsonpSsl" crossDomainScriptAccessEnabled="true">
          <security mode="Transport" />
      </binding>
  </webHttpBinding>
</bindings>
<behaviors>
    <serviceBehaviors>
       <behavior name="MyBehavior">
           <serviceMetadata httpGetEnabled="true" />
           <serviceDebug includeExceptionDetailInFaults="true" />
      </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
       <behavior name="MyBehavior">
          <webHttp />        
       </behavior>
    </endpointBehaviors>
</behaviors>
<services>
 <service behaviorConfiguration="MyBehavior" 
              name="MyWs.Service1">
            <endpoint address="" binding="webHttpBinding"
               bindingConfiguration="jsonp" contract="MyWs.IService1" 
               behaviorConfiguration="MyBehavior"/> 
            <endpoint address="" binding="webHttpBinding"
               bindingConfiguration="jsonpSsl" contract="MyWs.IService1" 
               behaviorConfiguration="MyBehavior"/>                        
     </service>
</services>

JQuery函数:

   $.ajax({
            type: "POST",
            url: "http://XXX.XXX.XXX.XXX/wcf/Service1.svc/GetData",
            data: '{"value":"2340"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccessCall,
            error: OnErrorCall
        });

        function OnSuccessCall(response) {
            alert(response);
        }


        function OnErrorCall(response) {
            alert(response.status + " " + response.statusText);
        }

WCF接口:

  [OperationContract]
    [WebInvoke(Method = "POST",
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);

方法实施:

 public string GetData(int value)
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
         new System.Web.Script.Serialization.JavaScriptSerializer();
        string json = oSerializer.Serialize(string.Format("You entered: {0}", value));
        return json;
    }

任何想法如何解决?

谢谢!

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

[OperationContract]
[WebGet( ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json,
        UriTemplate = "GetEmployeeJson")]
  List<EmployeeData> GetEmployeeJson();

的web.config

  <bindings>
      <webHttpBinding>
          <binding name="webHttpBindingWithJsonP"
                   crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
  </bindings>
  <behaviors>
      <serviceBehaviors>
          <behavior name="WcfExample.Service1Behavior">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
          <behavior name="WebBehavior">
              <webHttp/>
          </behavior>
      </endpointBehaviors>
  </behaviors>
  <services>
      <service behaviorConfiguration="WcfExample.Service1Behavior" name="WcfExample.Service1">
          <endpoint address="" binding="webHttpBinding" contract="WcfExample.IService1" bindingConfiguration="webHttpBindingWithJsonP" behaviorConfiguration="WebBehavior" />
      </service>
  </services>

jquery调用wcf服务

       $.ajax({
            type: "GET",
            contentType: "application/javascript",
            crossDomain: true,
            dataType: 'jsonp',
            cache: true,
            url: 'http://localhost:49349/Service1.svc/GetEmployeeJson',
            success: function (data) {
                var html = [];

                alert(data[0].lastname);


                $.each(data, function (index, value) {
                    $("#TableID").append("<tr><td>" + value.HREmpId + "</td><td>" + value.firstName + "</td><td>" + value.lastname + "</td><td>" + value.address + "</td><td>" + value.city + "</td></tr>");

                });


            },

            error: function (xhr, ajaxOptions, thrownError) {
                alert("here error");
                alert(thrownError);
                if (xhr != null) {

                    var err = JSON.parse(xhr.responseText); //you can throw a code-behinde Exception and it will automatically                                                 //render to a valid JSON string when we rerieve the responseText
                    alert("ErrorMessage: " + err.Message + " StackTrace: " + err.StackTrace);

                }
            }
        });