CORS WCF:对预检请求的响应未通过访问控制 [英] CORS WCF: Response to preflight request doesn't pass access control

查看:64
本文介绍了CORS WCF:对预检请求的响应未通过访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用WCF服务时遇到问题。



这是我的WCF

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

然后我按照教程



编辑:添加我的web.config



 <?xml version = 1.0 encoding = utf-8 <配置> < configSections> <!-有关Entity Framework配置的更多信息,请访问http://go.microsoft.com/fwlink/?LinkID=237468-> <部分名称= entityFramework type = System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,EntityFramework,Version = 6.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089 requirePermission = false /> < / configSections> <!-添加元素connectionStrings-> < connectionStrings> <添加名称= ConnectionString connectionString =数据源= 192.168.0.202;初始目录= example.KRIS; UID = sa;密码= ***** providerName = System.Data.sqlClient /> <添加名称=实体 connectionString = metadata = res://*/DBEntities.csdl | res://*/DBEntities.ssdl | res://*/DBEntities.msl; provider = System.Data.SqlClient ; provider connection string ="数据源= 192.168.0.202;初始目录= example.KRIS;用户ID = sa; password = ******; MultipleActiveResultSets = True; App = EntityFramework" 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> <!-添加元素扩展和服务-> <扩展名> < behaviorExtensions> < add name = crossOriginResourceSharingBehavior type = WcfService.CORSEnablingBehavior,WcfService,Version = 1.0.0.0,Culture = neutral /> < / behaviorExtensions> < /扩展名> <服务> < service behaviorConfiguration = serviceBehavior name = WcfService.ServiceRequest> <端点地址= behaviorConfiguration = web binding = webHttpBinding contract = WcfService.IServiceRequest /> < / service> < / services> <行为> <!-编辑值-> < serviceBehaviors> < behavior name = serviceBehavior> < serviceMetadata httpGetEnabled = false /> < serviceDebug includeExceptionDetailInFaults = true /> < /行为> < / serviceBehaviors> <!-添加元素端点-> < endpointBehaviors> <行为名称= web> < webHttp /> < crossOriginResourceSharingBehavior /> < /行为> < / endpointBehaviors> < /行为> <!-编辑协议映射-> < protocolMapping> < add binding = webHttpBinding scheme = http /> < / protocolMapping> < serviceHostingEnvironment aspNetCompatibilityEnabled = true multipleSiteBindingsEnabled = true /> < /system.serviceModel> < system.webServer> < modules runAllManagedModulesForAllRequests = true /> <!-要在调试期间浏览Web应用程序的根目录,请将下面的值设置为true。部署前设置为false以避免泄露Web应用程序文件夹信息。 -> < directoryBrowse enabled = true /> < /system.webServer> < entityFramework> < defaultConnectionFactory type = System.Data.Entity.Infrastructure.LocalDbConnectionFactory,EntityFramework> <参数> <参数值= mssqllocaldb /> < /参数> < / defaultConnectionFactory> <提供者> <提供者invariantName = System.Data.SqlClient type = System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer /> < / providers> < / entityFramework>< / configuration>  

解决方案

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

 受保护的void Application_BeginRequest(对象发送者,EventArgs e)
{
HttpContext.Current.Response.AddHeader( Access-Control-Allow-Origin, *);

if(HttpContext.Current.Request.HttpMethod == OPTIONS)
{
HttpContext.Current.Response.AddHeader( Access-Control-Allow-Methods, 获取,发布,选项,放置,删除);
HttpContext.Current.Response.AddHeader( Access-Control-Allow-Headers, Content-Type,Accept);
HttpContext.Current.Response.AddHeader( Access-Control-Max-Age, 1728000);
HttpContext.Current.Response.End();
}
}


I have problem with WCF service access.

This is my WCF

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

Then I following tutorial tutorial CORS

This is my service to get the data

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: {}
                });
            }
        };
    }]);

Then this is my controller

(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'));

Then when I run I have the error like:

Edit: add my 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>

解决方案

Put following code in global.asax because you need to allow methods which can be called clients.

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

这篇关于CORS WCF:对预检请求的响应未通过访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆