Ⅰ. はじめに
タイトルの通り「ASP.NET で CORSを有効にする方法」です。
Ⅱ. サンプルプログラム
Program.cs
var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(x => { x.AddDefaultPolicy(policy => { policy.AllowAnyHeader(); policy.AllowAnyMethod(); policy.AllowCredentials(); policy.WithOrigins(new string[] { "http://example1.com" }); // policy.SetIsOriginAllowed(origin => true); // 全ての Origin を許可する }); }); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthorization(); app.UseCors(); // 追加 app.MapControllers(); app.Run();
Controllers/TestController.cs
[HttpPost("test001")] public IActionResult GetStringTest001() { return Ok("test001"); }
実行結果
Originが example1.com の場合
Access-Control-Allow-* が出力される。
$ curl \ --request "OPTIONS" \ --header "Origin: http://example1.com" \ --header "Access-Control-Request-Method: POST" \ --dump-header - \ "http://localhost:5162/test/test001" HTTP/1.1 204 No Content Date: Tue, 17 Oct 2023 15:18:46 GMT Server: Kestrel Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: POST Access-Control-Allow-Origin: http://example1.com Vary: Origin
Originが example2.com の場合
Access-Control-Allow-* が出力されない。
$ curl \ --request "OPTIONS" \ --header "Origin: http://example2.com" \ --header "Access-Control-Request-Method: POST" \ --dump-header - \ "http://localhost:5162/test/test001" HTTP/1.1 204 No Content Date: Tue, 17 Oct 2023 15:20:38 GMT Server: Kestrel