Skip to content

51 .NET CORE调用AWS cloudfront sdk刷新缓存

Jinxin Chen edited this page Dec 11, 2019 · 1 revision

cdn刷新缓存,可以从cloud控制台刷新,在某些情况不允许登录控制台,则可以考虑通过 AWS SDK 来刷新缓存

环境准备

创建 .net core mvc 项目

添加 package

需要添加到package如下:

  • AWSSDK.Extensions.NETCore.Setup

  • AWSSDK.CloudFront

配置参数

在 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 = 

注册aws服务

在 Startup.cs 文件的 ConfigureServices 方法中添加:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
    services.AddAWSService<Amazon.CloudFront.IAmazonCloudFront>();

    ...
}

AddDefaultAWSOptions 方法由 AWSSDK.Extensions.NETCore.Setup 包提供,用于从 AWS 凭证文件读取配置信息

使用 IAmazonCloudFront 刷新缓存

测试是否成功调用

先测试是否可以正常连接到 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 ,则说明配置没有问题。

添加缓存刷新 Invalidation

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);

参考:

Clone this wiki locally