以下是一个使用ASP.NET Core和AWS无服务器的解决方案,解决了CORS问题。
首先,在ASP.NET Core应用程序的Startup.cs文件中,添加以下代码以启用跨域资源共享(CORS):
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// 添加其他服务配置...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAllOrigins");
// 添加其他中间件配置...
}
然后,在AWS无服务器应用程序的serverless.template文件中,添加以下代码以配置API网关和Lambda函数的CORS:
Resources:
ApiGatewayRestApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Cors:
AllowMethods: "'GET,OPTIONS,POST'"
AllowHeaders: "'Content-Type'"
AllowOrigins: "'*'"
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: bin/Release/netcoreapp3.1/publish/
Handler: MyLambdaFunction::MyHandler
Runtime: dotnetcore3.1
Events:
MyApiResource:
Type: Api
Properties:
RestApiId: !Ref ApiGatewayRestApi
Path: /my-api
Method: ANY
这些配置将允许来自任何来源的GET,OPTIONS和POST请求,并允许使用Content-Type标头。