简体   繁体   English

wcf服务的jQuery ajax POST错误

[英]jQuery ajax POST error for wcf service

This is cross-domain ajax request: 这是跨域的ajax请求:

$.ajax({
            type: "POST",
            dataType: "jsonp",
            contentType: "application/jsonp",
            data: '{"UserName":"newuser","Password":"pwd"}',
            crossDomain: true,
            async: false,
            url: "http://xxx.xx.xx.xx/MyService/SampleService.svc/GetData",
            jsonpCallback: function (jsonData) {
                console.log(jsonData);
                alert('Hi');
            },
            complete: function (request, textStatus) { 
                alert(request.responseText);
                alert(textStatus);
            },
            error: function (request, textStatus, errorThrown) {
                alert(textStatus);
            }
        });

This is my WCF REST service's method: 这是我的WCF REST服务的方法:

namespace SampleServiceRestAPI
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class SampleService : ISampleService 
{
   ...
   public string GetData(UserData userData)
   {
      string response = "Hi_" + userData.UserName;
      return response;
   }
   ...
}

Interface: 接口:

    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetData")]
    [OperationContract]
    string GetData(UserData userData);

Datacontract: 数据合同:

[DataContract]
public class UserData
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }
}

And thepart of web.config : 还有web.config

<system.web>
   <compilation debug="true" targetFramework="4.0"/>
   <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>    
</system.web>
<system.serviceModel>
<standardEndpoints>
  <webScriptEndpoint>
    <standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
  </webScriptEndpoint>
</standardEndpoints>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" >
  <serviceActivations>
    <add factory="System.ServiceModel.Activation.ServiceHostFactory" relativeAddress="SampleService.svc" service="SampleServiceRestAPI.SampleService"/>
  </serviceActivations>
</serviceHostingEnvironment>
<services>
  <service behaviorConfiguration="ServiceBehaviour" name="SampleServiceRestAPI.SampleService">
    <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
      bindingConfiguration="webWinBinding" contract="SampleServiceRestAPI.ISampleService" />        
  </service>
  <!--<service behaviorConfiguration="metadataBehavior" name="MyService">
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>-->
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true"  />
    </behavior>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <webHttpBinding>
    <binding name="webWinBinding" maxBufferSize="2147483647" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647">

      <readerQuotas maxArrayLength="100000" maxStringContentLength="2147483647" />
    </binding>
  </webHttpBinding>
</bindings>
</system.serviceModel>
  <!--<system.web.extensions>
  <scripting>
  <webServices>
    <jsonSerialization maxJsonLength="2147483644"/>
    <protocols>
      <add name="HttpPost"/>     
      <add name="HttpPostLocalhost"/>   
    </protocols>      
  </webServices>
</scripting>
</system.web.extensions>-->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
<appSettings>
  <add key="ErrorCodeFile" value="~/App_Data/ErrorCode.txt"/>
</appSettings>

The error I got in the Firebug: 我在Firebug中遇到的错误:

"NetworkError: 500 Internal Server Error - http://173.161.176.229/MyService/SampleService.svc/GetData?callback=undefined& {%22UserName%22:%22newuser%22,%22Password%22:%22pwd%22}&_=1369120080493" “NetworkError:500内部服务器错误- http://173.161.176.229/MyService/SampleService.svc/GetData?callback=undefined& {%22UserName%22:%22newuser%22%22Password%22:%22pwd%22}&_ = 1369120080493“

The 500 error indicates that somethings wrong on the serverside. 500错误表示服务器端出了点问题。 You should examine what is going wrong there. 您应该检查那里出了什么问题。 It is possible that you have to look into the WCF part. 您可能需要研究WCF部分。 Perharps this helps: http://msdn.microsoft.com/en-us/library/ms732023.aspx Perharps会有所帮助: http : //msdn.microsoft.com/en-us/library/ms732023.aspx

You cannot usually (see later) make HTTP POSTs to a service on a different domain to the originating one. 通常,您无法(请参阅稍后)在与原始域不同的域上对服务进行HTTP POST。 This is more commonly known as the Same origin policy concept and is a browser security limitation which 这通常称为“ 相同来源策略”概念,并且是浏览器安全限制,

prevents access to most methods and properties across pages on different sites 阻止跨不同站点上的页面访问大多数方法和属性

JSONP works be inserting a <script> tag with the src being the URL of the JSONP request, which is an HTTP GET request. JSONP工作方式是插入<script>标记,其中src是JSONP请求(即HTTP GET请求)的URL。 The error you are seeing is because the browser is attempting to GET the resource which is throwing a 500 Internal Server Error as I assume GET on that URL is not supported. 您看到的错误是因为浏览器尝试获取GET导致500 Internal Server Error的资源,因为我认为不支持该URL上的GET

If the JavaScript and WCF service are on the same domain you do not need to use JSONP and should be able to do a regular $.ajax() POST. 如果JavaScript和WCF服务位于同一域中,则无需使用JSONP,并且应该能够执行常规的$.ajax() POST。

If the (page in which the) JavaScript and the WCF service are not on the same domain, one way to allow the cross-domain request is to enable CORS on your server. 如果JavaScript和WCF服务所在的页面不在同一域中,则允许跨域请求的一种方法是在服务器上启用CORS Also, the browser must also support it . 另外, 浏览器也必须支持它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM