1。)无法执行从客户端到WCF服务的CORS请求。 2.)如何配置WCF以允许来自特定域的CORS请求?
我尝试使用一些配置设置,例如 crossDomainScriptAccessEnabled customHeaders 在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>
答案 0 :(得分:0)
尝试在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();
}
}