0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET CoreのStartup.csでappsettings.jsonに書いたCORSのURLを取得する

Posted at

ASP.NET Coreでappsettings.jsonの内容を読み込む方法として、
Startup.csで対応するクラスを設定してコントローラーで読み込む方法があります。
参考:dot net core アプリケーションでapplication.jsonを参照する

しかし、CORS(クロスオリジン要求:別サーバのクライアントからのAPI呼び出しを許可する)は
StartUp.csで設定するので、CORSのURLをappsettings.jsonに記載する場合は別の取得方法が必要です。

この場合、StartUpのコンストラクタで渡されたIConfigurationに対して
GetSection("任意のキー").Valueで設定値を直接取得することができます。

appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "CorsUrl": "https://localhost:12345"
}

Startup.cs
public class Startup
{
    public Startup(IConfiguration configuration) => this.Configuration = configuration;

    public IConfiguration Configuration { get; }
 
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyAPI", Version = "v1" });
        });

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    // appsettings.jsonから"CorsUrl"の値を取得して設定。
                    builder.WithOrigins(this.Configuration.GetSection("CorsUrl").Value)
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                });
        });
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?