1. ホーム
  2. javascript

[解決済み] IIS7でのクロスオリジンリソース共有の有効化

2023-01-24 17:37:22

質問

最近、Javascript のリクエストを別のドメインに投稿することに遭遇しました。 デフォルトでは、他のドメインへの XHR 投稿は許可されていません。

の指示に従い http://enable-cors.org/ の指示に従い、もう一方のドメインでこれを有効にしました。

<?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>
 </system.webServer>
</configuration>

<イグ

現在はすべて正常に動作していますが、動作している 200 レスポンスを返送する前に 405 レスポンスを返送しています。

Request URL:http://testapi.nottherealsite.com/api/Reporting/RunReport
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:origin, content-type, accept
Access-Control-Request-Method:POST
Connection:keep-alive
Host:testapi.nottherealsite.com
Origin:http://test.nottherealsite.com
Referer:http://test.nottherealsite.com/Reporting
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Response Headersview source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Allow:POST
Cache-Control:private
Content-Length:1565
Content-Type:text/html; charset=utf-8
Date:Tue, 18 Sep 2012 14:26:06 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

更新日:2014/3/02

最近更新された記事がMSDN誌に掲載されています。ASP.NET Web API 2のCORSサポートについて詳しく説明されています。

http://msdn.microsoft.com/en-us/magazine/dn532203.aspx

どのように解決するのですか?

HTTP OPTIONS レスポンスをアプリケーションが指定するのではなく、IIS 7 が「処理」している可能性があります。 これを判断するために、IIS7 では。

  1. サイトの「ハンドラ マッピング」に移動します。

  2. OPTIONSVerbHandler」までスクロールダウンします。

  3. ProtocolSupportModule'を'IsapiHandler'に変更します。

  4. 実行ファイルを設定します。 %windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll

これで、HTTP OPTIONS動詞が送信されたときに、上記の設定エントリが起動するはずです。

あるいは、BeginRequestメソッドでHTTP OPTIONS動詞に応答することができます。

    protected void Application_BeginRequest(object sender,EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
            HttpContext.Current.Response.End();
        }

    }