zukucode
主にWEB関連の情報を技術メモとして発信しています。

ASP.NET CORSの設定を行う

ASP.NETWebAPICORSの設定を行う方法を紹介します。

例えばWEBページのURLがlocalhost:3000で、WebAPIのURLがlocalhost:5000のとき、WEBページかAPIをAJAXでコールするときは、以下のようにCORSの設定をする必要があります。

Startup.csに以下を追記します。

URLは配列で指定することもできます。

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder =>
        {
            builder.WithOrigins("http://localhost:3000");
            builder.AllowAnyMethod();
            builder.AllowAnyHeader();
            builder.AllowCredentials();
        });
    });

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseCors();

    app.UseAuthentication();
    app.UseAuthorization();

CORSを設定するURLを設定ファイルから読み込む

CORSを設定するURLを設定ファイル(appsettings.json)から読み込むには以下のようにします。

まず設定ファイルにURLを追記します。

appsettings.json
{
  "Logging": {
    "LogLevel": {
    "Default": "Information",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedOrigins": ["http://localhost:3000"]
}

Startup.csを以下のように修正します。

設定ファイルから読み込むため、IConfigurationDIします。

Startup.cs
public IConfiguration Configuration { get; }

public Startup()
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder =>
        {
            builder.WithOrigins(Configuration.GetSection("AllowedOrigins").Get<string[]>();
            builder.WithOrigins("http://localhost:3000");

関連記事