英文:
Why are CORS header not present in Postman for this simple ASP.NET Core 7 Web API?
问题
I'm testing with the out of the box ASP.NET Core 7 Web API and try to add CORS headers with the AddCors() and UseCors() calls but the headers don't appear in Postman when I test the API call. This is how my program.cs file looks like. Why are these headers not present in the response? Thanks!
英文:
I'm testing with the out of the box ASP.NET Core 7 Web API and try to add CORS headers with the AddCors() and UserCors() calls but the headers don't appear in Postman when I test the API call. This is how my program.cs file looks like. Why are these headers not present in the response? Thanks!
var builder = WebApplication.CreateBuilder( args );
// Add services to the container.
builder.Services.AddCors( options =>
{
options.AddDefaultPolicy( builder =>
{
builder.WithOrigins( "https://flex.twilio.com" )
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
;
} );
} );
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.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
I already tried to move the app.UserCors() to different place but according to the documentation the app.UserCors() should be placed after the app.UseHttpsRedirection() call and before the app.UserAuthorisation() call.
答案1
得分: 1
Access-Control-Allow-Origin
只允许服务器指定 *
或 单个 源。
名称 WithOrigins
暗示了对多个源的支持。
要支持多个源,服务器必须检查 Origin
请求标头,将其与允许的源列表进行比较,并在匹配时添加 Access-Control-Allow-Origin
响应标头,其中包含特定允许的源。
您的截图显示您未从 Postman 发送 Origin
请求标头,因此它不会与任何允许的源匹配(您可以在 GUI 中将 Origin
添加为 https://flex.twilio.com
)。
英文:
(NB: I don't use ASP.NET. This answer is based on knowing how CORS works and how other libraries that support it handle multiple origins.)
Access-Control-Allow-Origin
only allows a server to specify *
or a single origin.
The name WithOrigins
implies the support for multiple origins.
To support multiple origins, the server has to examine the Origin
request header, compare it to the list of allowed origins, and add the Access-Control-Allow-Origin
response header with the specific allowed origin if there is a match.
Your screenshot shows that you aren't sending an Origin
request header from Postman so it won't match any of the allowed origins (you can add Origin
as https://flex.twilio.com
in the GUI).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论