跨源请求被阻止原因:CORS预检频道未成功

时间:2015-05-29 10:21:25

标签: wcf cross-domain phonegap-plugins nopcommerce

我已经创建了一个phonegap应用,我在其中调用了驻留在nopCommerce插件中的WCF服务。

我在发送api请求时遇到以下错误:

  

阻止跨源请求:同源策略禁止在http://testwebsite.com/Plugins/NopRestApi/RemoteService/WebService.svc/GetData读取远程资源。 (原因:CORS预检频道没有成功)。

     

阻止跨源请求:同源策略禁止在http://testwebsite.com/Plugins/NopRestApi/RemoteService/WebService.svc/GetData读取远程资源。 (原因:CORS请求失败)。

使用Ajax进行API调用

$.ajax({
  crossDomain: true,
  type: "POST",
  contentType: "application/json",
  async: false,
  url: "http://testwebsite.com/Plugins/NopRestApi/RemoteService/WebService.svc/GetData",
  data: "{storeId:" + storeId + ", languageId:" + languageId + ", customerId:" + customerId + "}",            
  //data: { storeId: storeId, languageId: languageId, customerId: customerId },
  dataType: 'json',
  //jsonp: false,
  success: function (data) {
      alert(data.d);                
  },
  error: function (xhr, textStatus, error) {
      alert("Error! " + error);                
  }
});

我已经通过谷歌的一些研究在我的Web.config文件中添加了以下内容。

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

我已尝试过很多方法,甚至通过How to temporarily disable XSS protection in modern browsers for testing?链接禁用浏览器跨域请求检查,但仍然存在同样的问题。

有没有人有类似问题并已解决?

谢谢!

3 个答案:

答案 0 :(得分:3)

在global.asax中:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires at the beginning of each request
    If Request.HttpMethod = "OPTIONS" Then
        Response.Flush()
    End If

End Sub

web.config中的allow方法也显示了OPTIONS。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="1000000" />
  </appSettings>

  <connectionStrings/>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5.1"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
      <namespaces>
        <clear/>
        <add namespace="System"/>
        <add namespace="System.Collections"/>
        <add namespace="System.Collections.Specialized"/>
        <add namespace="System.Configuration"/>
        <add namespace="System.Text"/>
        <add namespace="System.Text.RegularExpressions"/>
        <add namespace="System.Web"/>
        <add namespace="System.Web.Caching"/>
        <add namespace="System.Web.SessionState"/>
        <add namespace="System.Web.Security"/>
        <add namespace="System.Web.Profile"/>
        <add namespace="System.Web.UI"/>
        <add namespace="System.Web.UI.WebControls"/>
        <add namespace="System.Web.UI.WebControls.WebParts"/>
        <add namespace="System.Web.UI.HtmlControls"/>
      </namespaces>
    </pages>
    <authentication mode="Windows"/>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".apk" mimeType="application/octet-stream"/>
    </staticContent>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <remove name="OPTIONSVerbHandler"/>
      <remove name="TRACEVerbHandler"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="POST,OPTIONS,GET"/>
        <add name="Access-Control-Allow-Headers" value="Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, Accept"/>
        <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Cors" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="4000000" />
      </webServices>
    </scripting>
  </system.web.extensions>

</configuration>

很抱歉global.asax在VB中因为我是一个VB家伙,我想你可以把它转换成C#。

根据您的要求,更新如下:

function funCheckWS() {
    var tblLogin = {};
    tblLogin.strLoginName = "UserName";
    tblLogin.strPassword = "123456";
    jQuery.support.cors = true;
    $.ajax({
        type: 'POST',
        url: 'http://www.example.com/wsMain.asmx/funCheckWS',
        data: "{tblLogin:" + JSON.stringify(tblLogin) + "}",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        crossDomain: true,
        // async: false,
        async: true,
        success: function (r) {
            // Browser support WS
            gloBolWS = true;
            // alert("funCheck: " + r.d.strPassword);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            // Browser does not support WS
            //alert(xhr.status);
            //alert(thrownError);
        }
    });
}

下面是我在VB中的Web服务(clsSQL是一个用VB编写的类,包含我所有后端业务逻辑的功能,可以访问sql服务器):

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web

<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class wsMain
    Inherits System.Web.Services.WebService

    Private clsSQL As New wxdlSQL.clsSQL()

    Private tblLogin As tabLogin
    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Function funCheckWS(tblLogin As tabLogin) As tabLogin
        tblLogin.strLoginName += "Hello World"
        Return tblLogin
    End Function
End Class

下面是我如何定义参数的数据类型:

Public Class tabLogin
    Private _loginname As String
    Public Property strLoginName As String
        Get
            Return _loginname
        End Get
        Set(ByVal value As String)
            _loginname = value
        End Set
    End Property
    Private _password As String
    Public Property strPassword As String
        Get
            Return _password
        End Get
        Set(ByVal value As String)
            _password = value
        End Set
    End Property
End Class

答案 1 :(得分:3)

您需要允许来自WCF服务的跨域请求。

Response.AppendHeader("Access-Control-Allow-Origin", "*");

在你的函数中添加它,但在从函数返回数据之前添加它。

How to implement “Access-Control-Allow-Origin” header in asp.net可能会有所帮助。

答案 2 :(得分:1)

Global.asax中,添加以下代码:

protected void Application_AuthenticateRequest(object sender, EventArgs e){
    Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (Context.Request.HttpMethod.Equals("OPTIONS")){
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
        Context.ApplicationInstance.CompleteRequest();
     }
 }

那应该有用