几天前我在处理CORS问题,我需要支持多个起源。我做了一些研究,并发现了一对夫妇的帖子指向我这个伟大的工具(URL重写)。按照Paco Zarate的提示,我得到了我想要的解决方案。Access-control-allow-origin with multiple domains. 使用URL Rewrite。我在这里还发现了另一个帖子。http:/www.carlosag.netarticlesenable-cors-access-control-allow-origin.cshtml 向我展示了如何在URL Rewrite中用不同的配置方法实现相同的解决方案。
Paco Zarate的解决方案就像一个魅力。为什么我还在问问题?这只是为了学习的目的。而且我也认为第二个帖子的配置会产生一个更优雅的我想要白名单的originsdomains列表。为了方便维护,我可以直接到重写地图中查看我所有的AllowedOrigins。
当尝试第二篇帖子的解决方案时,我得到了这个消息。ERR_CONNECTION_RESET 在浏览器调试工具的Console选项卡下。而网络选项卡下的请求头显示 "临时头显示"
非常感谢。
我的配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed" />
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Accept" />
<add name="Access-Control-Request-Method" value="POST" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Origin" value="http://localhost:8080" />
</customHeaders>
</httpProtocol>
<rewrite>
<rules>
<rule name="Capture Origin Header">
<match url=".*" />
<conditions>
<add input="{HTTP_ORIGIN}" pattern=".+" />
</conditions>
<serverVariables>
<set name="CAPTURED_ORIGIN" value="{C:0}" />
</serverVariables>
<action type="None" />
</rule>
<rule name="Preflight Options" enabled="false" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^OPTIONS$" />
</conditions>
<action type="CustomResponse" statusCode="200" statusReason="Preflight" statusDescription="Preflight" />
</rule>
</rules>
<rewriteMaps>
<rewriteMap name="AllowedOrigins">
<add key="http://somedomain:8080" value="http://localhost:8080" />
</rewriteMap>
</rewriteMaps>
<outboundRules>
<rule name="Set-Access-Control-Allow-Origin for known origins">
<match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern=".+" negate="true" />
<conditions>
<add input="{AllowedOrigins:{CAPTURED_ORIGIN}}" pattern=".+" />
</conditions>
<action type="Rewrite" value="{C:0}" />
</rule>
</outboundRules>
</rewrite>
<tracing>
<traceFailedRequests>
<add path="*">
<traceAreas>
<add provider="WWW Server" areas="Rewrite" verbosity="Verbose" />
</traceAreas>
<failureDefinitions timeTaken="00:00:00" statusCodes="500" verbosity="Error" />
</add>
</traceFailedRequests>
</tracing>
</system.webServer>
我有很多的问题,试图使用URL重写模块启用CORS,经过大量的故障排除,我发现,对于IIS 7.5+你可以使用IIS CORS模块。https:/www.iis.netdownloadsmicrosoftiis-cors-module
你的web.config应该是这样的。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="http://localhost:8080" allowCredentials="true">
<allowMethods>
<add method="POST" />
</allowMethods>
</add>
</cors>
</system.webServer>
</configuration>
你可以在这里找到配置参考。https:/docs.microsoft.comen-usiisextensionscors-modulecors-module-configuration-reference。