-
Notifications
You must be signed in to change notification settings - Fork 0
51 .NET CORE调用AWS cloudfront sdk刷新缓存
Jinxin Chen edited this page Dec 11, 2019
·
1 revision
cdn刷新缓存,可以从cloud控制台刷新,在某些情况不允许登录控制台,则可以考虑通过 AWS SDK 来刷新缓存
在 appsettings.json 文件添加:
"AWS": {
"Profile": "local-test-profile",
"Region": "us-west-2"
}
这里 Profile 指的是 AWS 凭证文件的配置名称,凭证文件路径:%HOME%\.aws\credentials,没有则创建一个,然后在凭证文件中添加:
[local-test-profile]
aws_access_key_id =
aws_secret_access_key =
在 Startup.cs 文件的 ConfigureServices 方法中添加:
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
services.AddAWSService<Amazon.CloudFront.IAmazonCloudFront>();
...
}
AddDefaultAWSOptions 方法由 AWSSDK.Extensions.NETCore.Setup 包提供,用于从 AWS 凭证文件读取配置信息
先测试是否可以正常连接到 AWS,修改 HomeController 文件:
private readonly IAmazonCloudFront _cfClient;
public HomeController(IAmazonCloudFront cfClient)
{
this._cfClient = cfClient;
}
public async Task<IActionResult> Index()
{
var distributionId = "";
var request = new ListInvalidationsRequest();
request.DistributionId = distributionId;
var respose = await this._cfClient.ListInvalidationsAsync(request);
var ids = "";
foreach ( var d in respose.InvalidationList.Items)
{
ids += d.Id.ToString();
}
return Content(ids);
}
然后访问首页,如果可以正确输出 id ,则说明配置没有问题。
var request = new CreateInvalidationRequest();
var batch = new InvalidationBatch();
batch.CallerReference = DateTime.Now.Ticks.ToString();
batch.Paths = new Paths();
batch.Paths.Items.Add("/index.html");
batch.Paths.Quantity = batch.Paths.Items.Count;
request.DistributionId = distributionId;
request.InvalidationBatch = batch;
var response = await this._cfClient.CreateInvalidationAsync(request);
return Content(response.Invalidation.Status);
-
[Configuring the AWS SDK for .NET with .NET Core](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html)
-
[Configuring AWS Credentials](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html)