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?

OpenAPI(C#)でCORS request エラーを解決する

Posted at

1. はじめに

  • OpenAPIでswagger-uiを同一ドメイン、別ポートで起動した時にエラーが発生するのを解決したい
Server response Code
Details Undocumented Failed to fetch. Possible Reasons: CORS Network Failure URL scheme must be "http" or "https" for CORS request.

2. 開発環境

  • OpenAPI v3.0
  • C#
  • .NET 8.0
  • Windows

3. CORS(Cross-Origin Resource Sharing)とは

  • こちらのサイトを参考に理解した

4. ソースコード

  • 開発環境のため一旦すべて許可をするように修正する
Prgoram.cs
var builder = WebApplication.CreateBuilder(args);

+ // CORSポリシーを追加
+ builder.Services.AddCors(options =>
+ {
+     options.AddPolicy("AllowAllOrigins", policy =>
+     {
+         policy.AllowAnyOrigin()
+               .AllowAnyMethod()
+               .AllowAnyHeader();
+     });
+ });

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

+ app.UseCors("AllowAllOrigins");

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

5. 参考文献

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?