關於網路那些事...

網路行銷,SEO,網路趨勢,教學文章,網頁設計,生活時事

ASP.NET 啟用跨站API請求 “Access-Control-Allow-Origin”

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");

如果你喜歡我們的文章內容,請在這裡按個讚



最新文章推薦