【发布时间】:2020-09-05 06:32:27
【问题描述】:
说明
我正在使用 AWS Lambda 但没有 Amazon.Lambda.AspNetCoreServer 包,一切正常,除了我添加了一些基本的自定义响应标头(例如 JSON 内容类型)并且在最终 HTTP 响应中没有添加任何内容标题。
在我的特殊情况下,我没有使用Amazon.Lambda.AspNetCoreServer,因为我正在构建一个无服务器框架模板。
- 这是我的 Lambda 函数实现: https://github.com/RichardSilveira/UserServerlessMicroservice/blob/master/src/userService/Functions/GetUserByIdFunction.cs
public class GetUserByIdFunction : FunctionBase
{
private IUserRepository _userRepository;
protected override void ConfigureServices(IServiceCollection serviceCollection)
{
var connString = Configuration["UserServiceDbContextConnectionString"];
// serviceCollection.AddDbContext<UserContext>(options => options.UseMySql(connString));
serviceCollection.AddDbContext<UserContext>(options => options.UseInMemoryDatabase(connString));//temporarily
serviceCollection.AddScoped<IUserRepository, UserRepository>();
}
protected override void Configure(IServiceProvider serviceProvider)
{
_userRepository = serviceProvider.GetService<IUserRepository>();
}
// Invoked by AWS Lambda at runtime
public GetUserByIdFunction()
{
}
public GetUserByIdFunction(
IConfiguration configuration,
IUserRepository userRepository)
{
// Constructor used by tests
_userRepository = userRepository;
}
public async Task<APIGatewayHttpApiV2ProxyResponse> Handle(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
{
LogFunctionMetadata(request, context);
if (!RunningAsLocal) ConfigureDependencies();
var userId = Guid.Parse(request.PathParameters["userid"]);
var user = await _userRepository.GetByIdAsync(userId);
if (user == null) return NotFound();
return Ok(user);
}
}
public abstract class FunctionBase
{
protected IConfiguration Configuration { get; private set; }
protected bool RunningAsLocal = false;
public FunctionBase() => Configuration = ConfigurationService.Instance.Configuration;
public FunctionBase(IConfiguration configuration)
{
Configuration = configuration;
RunningAsLocal = true;
}
protected void ConfigureDependencies()
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
Configure(serviceCollection.BuildServiceProvider());
}
protected abstract void ConfigureServices(IServiceCollection serviceCollection);
protected abstract void Configure(IServiceProvider serviceProvider);
protected void LogFunctionMetadata(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
{
LambdaLogger.Log($"CONTEXT {Serialize(context.GetMainProperties())}");
LambdaLogger.Log($"EVENT: {Serialize(request.GetMainProperties())}");
}
protected APIGatewayHttpApiV2ProxyResponse Ok() =>
new APIGatewayHttpApiV2ProxyResponse()
{
StatusCode = (int) HttpStatusCode.OK,
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"}
}
};
protected APIGatewayHttpApiV2ProxyResponse NotFound() =>
new APIGatewayHttpApiV2ProxyResponse()
{
StatusCode = (int) HttpStatusCode.NotFound,
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"}
}
};
}
唯一的问题是添加到 APIGatewayHttpApiV2ProxyResponse 类的任何标头都没有按预期添加到最终的 HTTP 响应中。
注意:我已经尝试过使用它的SetHeaderValues,例如:
protected APIGatewayHttpApiV2ProxyResponse Ok(object body)
{
var response = new APIGatewayHttpApiV2ProxyResponse()
{
StatusCode = (int) HttpStatusCode.OK,
Body = Serialize(body)
};
response.SetHeaderValues("Content-Type", "application/json", false);
response.SetHeaderValues("Access-Control-Allow-Origin", "*", false);
response.SetHeaderValues("Access-Control-Allow-Credentials", "true", false);
return response;
}
复制步骤
git clone https://github.com/RichardSilveira/UserServerlessMicroservice
cd UserServerlessMicroservice
cd src/userService
npm i -g serverless
注意:无服务器框架在 Cloudformation 上创建了一个抽象层,这意味着将在 AWS 账户中部署一个堆栈,您可以轻松删除堆栈 - 您将上传的此堆栈不会收取任何费用。
provider:
name: aws
profile: default
runtime: dotnetcore3.1
stage: dev
region: sa-east-1
您可以通过添加
profile: <name>(如上例中的profile: <name>)从本地计算机AWS 凭证文件中的serverless.yml文件中通知配置文件名称。它是可选的,如果您什么都不做,将使用默认配置文件。
build
sls deploy -v
日志
不适用
环境
我认为最好展示我所有的项目描述文件。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<PackageId>aws-csharp</PackageId>
<RootNamespace>UserService</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.Core" Version="1.1.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.0.1" />
<PackageReference Include="EventStore.Client" Version="20.6.0" />
<PackageReference Include="FluentValidation" Version="9.0.1" />
<PackageReference Include="MediatR" Version="8.1.0" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.6" />
<PackageReference Include="MySql.Data" Version="8.0.21" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.2" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.dev.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.local.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
有什么想法吗?
提前致谢!
【问题讨论】:
标签: aws-lambda serverless-framework aws-serverless aws-sdk-net