![](/img/trans.png)
[英]403 Forbidden/500 Internal Server Error after deploying .net core api AWS Serverless application
[英]Internal Server Error returned when accessing aws Serverless API deployed to AWS API gateway
我正在嘗試部署可操縱AWS DynamoDB數據庫的API。 我使用了AWS .Net SDK提供的無服務器API模板。 .Net Core API在本地運行良好,但是在將其發布到AWS Lambda之后,每當我嘗試訪問該API時,都會返回“內部服務器錯誤”。
在CloudWatch Logs Insights中,日志消息返回如下內容
調用'ProjectAPI.Controllers.MyController'類型的構造函數時,引發了異常。 檢查內部異常以獲取更多詳細信息。:LambdaException
在System.RuntimeTypeHandle.CreateInstance(RuntimeType類型,布爾publicOnly,布爾wrapExceptions,布爾&canBeCached,RuntimeMethodHandleInternal&ctor)
在System.RuntimeType.CreateInstanceSlow處(布爾publicOnly,布爾wrapExceptions,布爾skipCheckThis,布爾fillCache)
在MyController的構造函數中,我實例化了一個服務,該服務將獲取憑據並設置DynamoDBContext。
在MyController中:
private readonly IMyService _myService;
public CoffeeController(IMyService myService){
_myService = myService;
}
在MyService中:IMyService
private readonly DynamoDBContext _context;
public CoffeeService()
{
var chain = new CredentialProfileStoreChain();
AWSCredentials awsCredentials;
if (chain.TryGetAWSCredentials("Hackathon-coffee", out awsCredentials)){
AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentials, RegionEndpoint.APSoutheast2);
_context = new DynamoDBContext(client, new DynamoDBContextConfig { ConsistentRead = true, SkipVersionCheck = true });
}else
LambdaLogger.Log("Cannot Fetch Credentials");
}
在Startup.cs中:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IMyService, MyService>();
}
我認為獲取憑據時出了點問題,但是我不確定如何在.Net Core環境中適當地進行操作。
我假設"Hackathon-coffee"
是指存儲在本地開發環境中的憑據配置文件。 該配置文件在Lambda環境中將不存在。
在Lambda中,您很可能希望使用在創建Lambda函數時分配給IAM角色的憑據。
基本上,當在Lambda中運行時,您想要構建AmazonDynamoDBClient
而不傳遞AWSCredentials
。 SDK會自動為分配的角色解析憑據。 對於構造函數中的region參數也是如此。 如果您使用空構造函數構造一個AmazonDynamoDBClient
,它將為客戶端配置IAM角色和運行該功能的區域的憑證。
有時,我會在代碼中使用一個方便的技巧來判斷我是否在Lambda中運行,請檢查是否設置了LAMBDA_TASK_ROOT
環境變量。
private readonly DynamoDBContext _context;
public CoffeeService()
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TASK_ROOT")))
{
var chain = new CredentialProfileStoreChain();
AWSCredentials awsCredentials;
if (chain.TryGetAWSCredentials("Hackathon-coffee", out awsCredentials))
{
AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentials, RegionEndpoint.APSoutheast2);
_context = new DynamoDBContext(client, new DynamoDBContextConfig { ConsistentRead = true, SkipVersionCheck = true });
}
else
{
LambdaLogger.Log("Cannot Fetch Credentials");
}
}
else
{
// Use credentials from IAM Role and region the function is running in.
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
_context = new DynamoDBContext(client, new DynamoDBContextConfig { ConsistentRead = true, SkipVersionCheck = true });
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.