【问题标题】:jQuery ajax POST error for wcf servicewcf服务的jQuery ajax POST错误
【发布时间】:2013-05-21 07:15:35
【问题描述】:

这是跨域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);
            }
        });

这是我的 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;
   }
   ...
}

界面:

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

数据合约:

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

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

还有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>

我在 Firebug 中遇到的错误:

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

【问题讨论】:

  • JSONP 只适用于 GET 请求,而不适用于 POST

标签: jquery asp.net ajax wcf web-services


【解决方案1】:

500 错误表示服务器端出现问题。你应该检查那里出了什么问题。您可能必须查看 WCF 部分。 Perharps 这有帮助:http://msdn.microsoft.com/en-us/library/ms732023.aspx

【讨论】:

    【解决方案2】:

    您不能通常(见下文)将 HTTP POST 发送到与原始域不同的域上的服务。这通常称为Same origin policy 概念,是一种浏览器安全限制,

    阻止访问不同站点上跨页面的大多数方法和属性

    JSONP 可以插入一个&lt;script&gt; 标记,其中src 是JSONP 请求的URL,这是一个HTTP GET 请求。您看到的错误是因为浏览器试图 GET 抛出 500 Internal Server Error 的资源,因为我认为该 URL 上的 GET 不受支持。

    如果 JavaScript 和 WCF 服务在同一个域中,则您不需要使用 JSONP,并且应该能够执行常规的$.ajax() POST。

    如果(页面)JavaScript 和 WCF 服务不在同一个域中,允许跨域请求的一种方法是在您的服务器上启用 CORS。此外,browser must also support it .

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 2012-03-05
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      相关资源
      最近更新 更多