如何允许CORS请求WCF中的特定域



1。(无法从客户端向WCF服务进行CORS请求。2.(如何配置WCF允许从特定域中的CORS请求?

我尝试使用一些配置设置 CrossDomainscriptAccesseNabled 定制者在web.config中,但仍然给CORS错误。

帮助我根据其域名或IP自定义对特定请求的访问。

 <system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
  </webHttpBinding>
</bindings>
<behaviors>
 <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="EndPointBehaviour">
      <webHttp/>
      <enableWebScript />
    </behavior>
  </endpointBehaviors>

</behaviors>
<services>
  <service name="MyNameSpace.MyService" behaviorConfiguration="ServiceBehaviour">
   <endpoint 
      address="" behaviorConfiguration="EndPointBehaviour"
      binding="webHttpBinding"
      contract="MyNameSpace.IMyService" bindingConfiguration="crossDomain" />    
  </service>
</services>
<protocolMapping>
  <add binding="webHttpBinding" scheme="http" bindingConfiguration="crossDomain" />
  <add binding="basicHttpsBinding" scheme="https"/>
</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"/>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Max-Age" value="1728000" />
  </customHeaders>
</httpProtocol>

在global.asax.cs文件中尝试使用此代码:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, 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();
    }
}

最新更新