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

imm*_*odi 6 wcf cross-domain nopcommerce phonegap-plugins

我创建了一个phonegap应用程序,我正在调用WCF服务,该服务位于nopCommerce插件中.

我在发送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);                
  }
});
Run Code Online (Sandbox Code Playgroud)

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

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多方法甚至禁用浏览器跨源请求检查通过以下如何暂时禁用现代浏览器中的XSS保护进行测试?链接但仍然存在同样的问题.

有没有人有类似的问题并解决了?

谢谢!

Ken*_* Li 4

在全局.asax中:

\n\n
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)\n    \' Fires at the beginning of each request\n    If Request.HttpMethod = "OPTIONS" Then\n        Response.Flush()\n    End If\n\nEnd Sub\n
Run Code Online (Sandbox Code Playgroud)\n\n

web.config 中的允许方法也显示添加选项。

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

抱歉,global.asax 是用 VB 编写的,因为我是 VB 人员,我认为您可以将其转换为 C#。

\n\n

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

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

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

\n\n
Imports System.Web.Services\nImports System.Web.Services.Protocols\nImports System.ComponentModel\nImports System.Web.Script.Serialization\nImports System.Web.Script.Services\nImports System\nImports System.Collections.Generic\nImports System.Linq\nImports System.Web\n\n<System.Web.Script.Services.ScriptService()> _\n<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _\n<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _\n<ToolboxItem(False)> _\nPublic Class wsMain\n    Inherits System.Web.Services.WebService\n\n    Private clsSQL As New wxdlSQL.clsSQL()\n\n    Private tblLogin As tabLogin\n    <WebMethod()> _\n    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _\n    Public Function funCheckWS(tblLogin As tabLogin) As tabLogin\n        tblLogin.strLoginName += "Hello World"\n        Return tblLogin\n    End Function\nEnd Class\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
Public Class tabLogin\n    Private _loginname As String\n    Public Property strLoginName As String\n        Get\n            Return _loginname\n        End Get\n        Set(ByVal value As String)\n            _loginname = value\n        End Set\n    End Property\n    Private _password As String\n    Public Property strPassword As String\n        Get\n            Return _password\n        End Get\n        Set(ByVal value As String)\n            _password = value\n        End Set\n    End Property\nEnd Class\n
Run Code Online (Sandbox Code Playgroud)\n