ASP.NET 啟用跨站API請求 “Access-Control-Allow-Origin” 簡易設定方式有兩種

1.設定 web.config

在 web.config 加入

<httpProtocol>
<customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://172.17.153.69:8100" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>

例如:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        
        <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="http://172.17.153.69:8100" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
            <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
        </customHeaders>
        </httpProtocol>

        <httpErrors errorMode="Detailed" />
    </system.webServer>
</configuration>

2.在aspx.cs 加入 responsive header

如果沒有配置IIS的權限 可以直接在 aspx.cs 檔案中設定

Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Response.AppendHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");

另外,若API回傳為JSON,建議額外添加 json 格式宣告

Response.AppendHeader("Content-Type", "application/json; charset=utf-8");