最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

CORS error when using SwaggerOpenAI in .NET 9 Aspire Application - Stack Overflow

programmeradmin1浏览0评论

I am trying to configure my .NET 9 Aspire App Web API with OpenAI to use Swagger. I tried the code at this link, but I get CORS error when I try to execute in Swagger UI:

.0

The example works if the API is standalone (not orchestrated in Aspire). What do I need to do to get this to work in Aspire?

NOTE: I tried with Scalar as well but it just failed the fetch; did not give me an error message.

I am trying to configure my .NET 9 Aspire App Web API with OpenAI to use Swagger. I tried the code at this link, but I get CORS error when I try to execute in Swagger UI:

https://learn.microsoft/en-us/aspnet/core/fundamentals/openapi/using-openapi-documents?view=aspnetcore-9.0

The example works if the API is standalone (not orchestrated in Aspire). What do I need to do to get this to work in Aspire?

NOTE: I tried with Scalar as well but it just failed the fetch; did not give me an error message.

Share Improve this question asked Nov 20, 2024 at 20:45 Douglas MarquardtDouglas Marquardt 994 bronze badges 1
  • 1 The "servers" list under the OpenAPI "localhost:port/openapi/v1.json" have different ports than the Web API. Which causes CORS issues. Aspire seems to influence the OpenAPI, causing it to generate different ports than the ones stated in the launchSettings.json. Not sure how to solve it right now – HenrikP Commented Nov 21, 2024 at 17:59
Add a comment  | 

2 Answers 2

Reset to default 5

A solution for Scalar is to empty the server list:

app.MapScalarApiReference(options =>
{
    options.Servers = [];
});

Credit to: https://github/dotnet/aspnetcore/issues/57332#issuecomment-2479286855

I am uncertain how to do this for Swagger with OpenAPI.

You need to enable CORS

builder.Services.AddCors(options =>
{
    options.AddPolicy("GetorPost",
        builder =>
        builder.AllowAnyOrigin().WithMethods("GET", "POST")
        .AllowAnyHeader());
});

//.....

if (app.Environment.IsDevelopment())
{
    app.UseCors("GetorPost");
}
发布评论

评论列表(0)

  1. 暂无评论