1. 程式人生 > >react .net core 釋出 Access-Control-Allow-Origin Cors

react .net core 釋出 Access-Control-Allow-Origin Cors

本案例用IIS部署

1. 在react上先publish: npm run build

生成了build檔案,在此檔案裡新增web.config,注意httpProtocol是用來跨域的。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>

<rewrite>
<rules>
<rule name="ReactRouter Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(docs)" negate="true" />
</conditions>
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

 

該檔案新增完畢以後,可以在IIS上部署起來,基本都是預設配置,配置完以後可以去HTTP Response Headers裡檢視一下web.config的內容有沒有。

 

2. publish .net core專案,此操作無其他特別要求,生成以後放入IIS新的站點裡。

值得注意的是,.net core 的cors需要這麼做:

由於我們這次是API,所以controller這裡這麼用:

當然如果你需要部分跨域,可以在method這裡加,我們因為全都需要,所以就在最開頭加了。

希望對大家有幫助。