当前位置: 首页 > 知识库问答 >
问题:

跨源请求受阻原因:CORS预飞通道未成功

百里芷阳
2023-03-14

我已经创建了一个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>

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

是否有人有类似的问题并已解决?

谢谢

共有3个答案

澹台华晖
2023-03-14

在您的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();
     }
 }

这应该行得通

佴英奕
2023-03-14

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

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

将其添加到函数中,但在数据从函数返回之前添加。

如何在asp.net中实现“Access Control Allow Origin”标题可能会有所帮助。

熊博远
2023-03-14

在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方法也显示addoptions。

<?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 server):

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
 类似资料:
  • 我试图在本地构建一个用PHP REST框架作为我的api的Ember应用程序。Ember应用程序在提供,而api只在提供。这导致了一个CORS问题。我已经尝试了我能想到的一切,但我不断得到一个错误返回,说请求被阻止,飞行前通道没有成功。它在Firefox或Chrome上都不成功。 我已经将以下内容添加到API的文件中: 有什么想法或解决办法吗?任何帮助都很感激。谢了!

  • 我有这个映射: 我正在使用控制器SpringBoot,我的控制器是 我将注释添加到所有存储库 主要类别是: 我添加了文件MyConfiguration(如爵士提议的那样) 前端(角度6) 因此,我想向使用这种方法的用户添加一个专家列表: 在哪里 你有解决这个问题的想法吗?。谢谢。

  • 如何通过 ajax 从远程 url 获取内容? jQuery ajax请求被阻止,因为跨源 控制台日志 跨来源请求被阻止:同一来源策略不允许读取http://www.dailymotion.com/embed/video/x28j5hv.的远程资源(原因:CORS标头“Access-Control-Allow-Origin”缺失)。 已阻止跨源请求:同源策略不允许读取位于的远程资源http://w

  • 问题内容: 这是我的配置: 现在,当我尝试访问我的API时,出现以下错误: 我在做什么错,以及如何正确配置CORS标头以避免发生此问题? 问题答案: 我已经通过创建新的CORS过滤器解决了此问题: 并将其添加到安全配置中: 更新-如今,我使用了更现代的方式切换到:

  • 我需要添加CORS过滤器到我的Spring Boot web应用程序。 我添加了CORS映射,如下文所述http://docs.spring.io/spring/docs/current/spring-framework-reference/html/CORS.html 这是我的配置:

  • 我已经在我的ASP中启用了CORS。NET MVC API,使用以下代码: 我尝试从API获取数据,打开localhost:6320/API/users,它工作了,我获取了所有数据。现在,当我尝试从Angular 7应用程序获取数据时,数据未加载,出现错误 “访问位于的XMLHttpRequest”http://localhost:6320/api/users“起源”http://localhos