CORS WCF:对预检请求的响应未通过访问控制

Posted

技术标签:

【中文标题】CORS WCF:对预检请求的响应未通过访问控制【英文标题】:CORS WCF: Response to preflight request doesn't pass access control 【发布时间】:2017-04-28 04:51:55 【问题描述】:

我在访问 WCF 服务时遇到问题。

这是我的 WCF

[OperationContract]
    [WebInvoke(
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, Method = "POST",
        UriTemplate = "/GetAllRequest/")]    
    IEnumerable<USP_GET_DATA_Result> Get();

然后我跟着教程tutorial CORS

这是我获取数据的服务

function (app) 
    app.service('AngularService', ['$http', function ($http) 
        return 
            get: function () 
                return $http(
                    method: 'POST',
                    headers: 
                        'Content-Type': 'application/json; charset=utf-8'
                    ,
                    url: 'http://localhost:51458/ServiceRequest.svc/GetAllRequest/',
                    data: 
                );
            
        ;
    ]);

那么这是我的控制器

(function (app) 
    'use strict';

    app.controller('entryCtrl', entryCtrl);

    entryCtrl.$inject = ['$scope', '$http', 'AngularService'];

    function entryCtrl($scope, $http, AngularService) 
        $scope.pageClass = 'page-entry';

        //load data
        AngularService.get().success(function (response) 
            $scope.entryData = JSON.parse(response.d);
        );

    

)(angular.module('entry'));

然后,当我运行时,出现如下错误:

编辑:添加我的 web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <!--add element connectionStrings-->
  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=192.168.0.202; Initial Catalog=example.KRIS; UID=sa; Password=*****" providerName="System.Data.sqlClient" />
    <add name="Entities" connectionString="metadata=res://*/DBEntities.csdl|res://*/DBEntities.ssdl|res://*/DBEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=192.168.0.202;initial catalog=example.KRIS;user id=sa;password=******;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.serviceModel>
    <!--add element extensions and services-->
    <extensions>
      <behaviorExtensions>
        <add name="crossOriginResourceSharingBehavior" 
             type="WcfService.CORSEnablingBehavior, 
             WcfService, Version=1.0.0.0, Culture=neutral" />
      </behaviorExtensions>
    </extensions>
    <services>
      <service behaviorConfiguration="serviceBehavior" name="WcfService.ServiceRequest">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="WcfService.IServiceRequest" />
      </service>
    </services>
    <behaviors>
      <!--edit value-->
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <!--add element endpoint-->
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
          <crossOriginResourceSharingBehavior />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <!--edit protocolmapping-->
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

【问题讨论】:

【参考方案1】:

将以下代码放入global.asax,因为您需要允许可以称为客户端的方法。

protected void Application_BeginRequest(object sender, EventArgs e)

   HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

   if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
   
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
      HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
      HttpContext.Current.Response.End();
    

【讨论】:

您在我的项目 WCF 或我的应用程序中挖掘 global.asax 吗?在我的 WCF 项目中没有 global.asax。然后已经放到我的应用上面protected void Application_Start() AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); 这个还是报错 在你的WCF service global.asax 您可以在wcf中新建一个global.asax文件 错误已更改Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:54801' is therefore not allowed access. 错误或这样的The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:54801' is therefore not allowed access.

以上是关于CORS WCF:对预检请求的响应未通过访问控制的主要内容,如果未能解决你的问题,请参考以下文章

为啥 CORS 错误“对预检请求的响应未通过访问控制检查”?

CORS:对预检请求的响应未通过访问控制检查

CORS 问题 - 对预检请求的响应未通过访问控制检查:

cors(cors 策略:对预检请求的响应未通过访问控制检查)角度 7 中的错误

从 JavaScript 访问 WCF WebService - 对预检请求的响应未通过访问控制检查

OAuth 中的 CORS:对预检请求的响应未通过访问控制检查