Select Page

要用 ASP.NET MVC 開發 WEB API給大家使用,前端 javascript 工程師,總是會遇到錯誤訊息 Response to preflight request doesn’t pass access control check: It does not have HTTP ok status,這是一個超常見的 CORS (Cross-Origin Resource Sharing) – 跨來源資源共用錯誤訊息,網路上很多解法,但可以用的情境都不太一樣,我這邊提供一個我覺得最簡單請快速的方法給大家。

解決方法是利用 NuGet 先安裝 Cors 套件

先上 NuGet 搜尋 Microsoft.AspNet.Cors , Microsoft.AspNet.WebApi.Cors,並且安裝起來

將 Cors 註冊起來

在 App_Start/WebApiConfig.cs 的 Register function 加入以下的程式碼

config.EnableCors();

會是長成以下的程式碼

        public static void Register(HttpConfiguration config)
        {
            // Web API 設定和服務
            config.EnableCors();

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

設定 WebAPI 的CORS 權限

我們可以在 WebApi 的 Class 上面設定,也可以在 Function 上做標記,但要注意的是不能有多個 CORS 繫結,如果你在 web.config 中設定,這邊就不能再做設定,如果你在 class 等級上設定了, function 等級就不能再設定,也是因為這個原因,所以我喜歡在 function 等級設定或是 class 等級上設定,web.config 比較少去做設定,雖然他有不用修改程式碼的好處。

其中設定值的資料參考請看https://docs.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference

  • origins,可以設定 (*) ,也可以指定特定網域,看你要對誰開放
  • headers,通常用 (*) 就可以了
  • methods,通常用 (*) 就可以了
    [System.Web.Http.Cors.EnableCors(origins: "https://yourdomain.com", headers: "*", methods: "*")]
    public class ValueController : ApiController
    {
    }

CORS web.config 的設定方法

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">
            <add origin="*" />
            <add origin="https://*.yourdomain.com"
                 allowCredentials="true"
                 maxAge="120"> 
                <allowHeaders allowAllRequestedHeaders="true">
                    <add header="header1" />
                    <add header="header2" />
                </allowHeaders>
                <allowMethods>
                     <add method="DELETE" />
                </allowMethods>
                <exposeHeaders>
                    <add header="header1" />
                    <add header="header2" />
                </exposeHeaders>
            </add>
            <add origin="http://*" allowed="false" />
        </cors>
    </system.webServer>
</configuration>