ASP.Net 中的 Amazon CloudFront 失效

发布于 2024-09-17 16:37:02 字数 341 浏览 9 评论 0原文

我不确定如何使用 ASP.Net 向 Amazon CloudFront 发送请求以使对象失效。

详细信息位于此处 http://docs.amazonwebservices.com/ AmazonCloudFront/latest/DeveloperGuide/index.html?Invalidation.html 但我不知道如何在 ASP.Net 中实现这一点。

I am not sure how to send a request using ASP.Net to Amazon CloudFront to invalidate an object.

The details are here http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?Invalidation.html
but I am not sure how to implement this in ASP.Net.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

顾北清歌寒 2024-09-24 16:37:02

从最新版本的适用于 .NET 的 AWS 开发工具包 (1.5.8.0) 开始,接受的答案不再有效。这应该可以解决问题:

using Amazon;
using Amazon.CloudFront.Model;

...

var client = AWSClientFactory.CreateAmazonCloudFrontClient(accessKey, secretKey);
client.CreateInvalidation(new CreateInvalidationRequest {
    DistributionId = distributionID,
    InvalidationBatch = new InvalidationBatch {
        Paths = new Paths {
            Quantity = arrayofpaths.Length,
            Items = arrayofpaths.ToList()
        },
        CallerReference = DateTime.Now.Ticks.ToString()
    }
});

The accepted answer no longer works as of the latest version of the AWS SDK for .NET (1.5.8.0). This should do the trick:

using Amazon;
using Amazon.CloudFront.Model;

...

var client = AWSClientFactory.CreateAmazonCloudFrontClient(accessKey, secretKey);
client.CreateInvalidation(new CreateInvalidationRequest {
    DistributionId = distributionID,
    InvalidationBatch = new InvalidationBatch {
        Paths = new Paths {
            Quantity = arrayofpaths.Length,
            Items = arrayofpaths.ToList()
        },
        CallerReference = DateTime.Now.Ticks.ToString()
    }
});
眼泪也成诗 2024-09-24 16:37:02

让它工作了,如果其他人发现它有用的话,就在这里。

    public static void InvalidateContent(string distributionId, string fileName)
    {
        string httpDate = Helpers.GetHttpDate();

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = @"<InvalidationBatch>" +
                            "   <Path>/" + fileName + "</Path>" +
                            "   <CallerReference>" + httpDate + "</CallerReference>" +
                            "</InvalidationBatch>";
        byte[] data = encoding.GetBytes(postData);

        // Prepare web request...
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation");
        webRequest.Method = "POST";
        webRequest.ContentType = "text/xml";
        webRequest.Headers.Add("x-amz-date", httpDate);

        Encoding ae = new UTF8Encoding();
        HMACSHA1 signature = new HMACSHA1(ae.GetBytes(GlobalSettings.AWSSecretAccessKey.ToCharArray()));
        string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));
        webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + GlobalSettings.AWSAccessKeyId + ":" + b64);

        webRequest.ContentLength = data.Length;

        Stream newStream = webRequest.GetRequestStream();
        // Send the data.
        newStream.Write(data, 0, data.Length);
        newStream.Close();
    }

    /// <summary>
    /// Gets a proper HTTP date
    /// </summary>
    public static string GetHttpDate()
    {
        // Setting the Culture will ensure we get a proper HTTP Date.
        string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
        return date;
    }

Got it working, here it is if anyone else finds it useful.

    public static void InvalidateContent(string distributionId, string fileName)
    {
        string httpDate = Helpers.GetHttpDate();

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = @"<InvalidationBatch>" +
                            "   <Path>/" + fileName + "</Path>" +
                            "   <CallerReference>" + httpDate + "</CallerReference>" +
                            "</InvalidationBatch>";
        byte[] data = encoding.GetBytes(postData);

        // Prepare web request...
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation");
        webRequest.Method = "POST";
        webRequest.ContentType = "text/xml";
        webRequest.Headers.Add("x-amz-date", httpDate);

        Encoding ae = new UTF8Encoding();
        HMACSHA1 signature = new HMACSHA1(ae.GetBytes(GlobalSettings.AWSSecretAccessKey.ToCharArray()));
        string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));
        webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + GlobalSettings.AWSAccessKeyId + ":" + b64);

        webRequest.ContentLength = data.Length;

        Stream newStream = webRequest.GetRequestStream();
        // Send the data.
        newStream.Write(data, 0, data.Length);
        newStream.Close();
    }

    /// <summary>
    /// Gets a proper HTTP date
    /// </summary>
    public static string GetHttpDate()
    {
        // Setting the Culture will ensure we get a proper HTTP Date.
        string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
        return date;
    }
柳若烟 2024-09-24 16:37:02

这是上面的 python 版本,如果有人觉得有用的话

from datetime import datetime
import urllib2, base64, hmac, hashlib

def getHTTPDate():
    return datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")

def submitInvalidationRequest(fileName,distributionId):
    url = "https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation"
    httpDate = getHTTPDate();
    postData = "<InvalidationBatch>" +"<Path>/" + fileName + "</Path>" +"<CallerReference>" + httpDate + "</CallerReference>" +"</InvalidationBatch>";
    sig = hmac.new(AWSSecretAccessKey, unicode(httpDate), hashlib.sha1)

    headers = {"ContentType": "text/xml",
           "x-amz-date": httpDate,
           "Authorization":"AWS " + AWSAccessKeyId + ":" +  base64.b64encode( sig.digest() )}

    req = urllib2.Request(url,postData,headers)
    return urllib2.urlopen(req).read()

Here's a python version of the above, if anyone finds it useful

from datetime import datetime
import urllib2, base64, hmac, hashlib

def getHTTPDate():
    return datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")

def submitInvalidationRequest(fileName,distributionId):
    url = "https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation"
    httpDate = getHTTPDate();
    postData = "<InvalidationBatch>" +"<Path>/" + fileName + "</Path>" +"<CallerReference>" + httpDate + "</CallerReference>" +"</InvalidationBatch>";
    sig = hmac.new(AWSSecretAccessKey, unicode(httpDate), hashlib.sha1)

    headers = {"ContentType": "text/xml",
           "x-amz-date": httpDate,
           "Authorization":"AWS " + AWSAccessKeyId + ":" +  base64.b64encode( sig.digest() )}

    req = urllib2.Request(url,postData,headers)
    return urllib2.urlopen(req).read()
记忆里有你的影子 2024-09-24 16:37:02

使用 来自 amazon 的 AWSSDK .net api 包装器 使此任务变得更加容易。

using Amazon.CloudFront.Model;

...

var client = Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(ConfigurationManager.AppSettings["Aws.AccessKey"],
                                                              ConfigurationManager.AppSettings["Aws.SecretKey"]);
var request = new PostInvalidationRequest();
request.DistributionId = ConfigurationManager.AppSettings["Cdn.DistributionId"];
request.InvalidationBatch = new InvalidationBatch();
request.InvalidationBatch.CallerReference = new Guid().ToString();
request.InvalidationBatch.Paths = PathsInput.Text.Split(new[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries).ToList();
var response = client.PostInvalidation(request);

using the AWSSDK .net api wrapper from amazon makes this task even easier.

using Amazon.CloudFront.Model;

...

var client = Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(ConfigurationManager.AppSettings["Aws.AccessKey"],
                                                              ConfigurationManager.AppSettings["Aws.SecretKey"]);
var request = new PostInvalidationRequest();
request.DistributionId = ConfigurationManager.AppSettings["Cdn.DistributionId"];
request.InvalidationBatch = new InvalidationBatch();
request.InvalidationBatch.CallerReference = new Guid().ToString();
request.InvalidationBatch.Paths = PathsInput.Text.Split(new[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries).ToList();
var response = client.PostInvalidation(request);
眼眸里的那抹悲凉 2024-09-24 16:37:02

这是珀尔:

use warnings;
use strict;
use HTTP::Date;
use Digest::SHA qw(hmac_sha1);
use LWP::UserAgent;
use MIME::Base64;
use Encode qw(encode_utf8);

@ARGV == 4 || die "usage: $0 url distribution_id accesskey secretkey\n";

my $invalid_url = $ARGV[0];
my $distribution_id = $ARGV[1];
my $accesskey = $ARGV[2];
my $secretkey = $ARGV[3];

my $url = "https://cloudfront.amazonaws.com/2010-11-01/distribution/$distribution_id/invalidation";
my $date = time2str;

my $post_data = <<HERE;
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch>
  <Path>$invalid_url</Path>
  <CallerReference>$date</CallerReference>
</InvalidationBatch>
HERE

my $sig = encode_base64(hmac_sha1(encode_utf8($date),encode_utf8($secretkey)));

my $browser = LWP::UserAgent->new;
my $res = $browser->post($url,
                         "Content" => $post_data,
                         "ContentType" => "text/xml",
                         "x-amz-date" => $date,
                         "Authorization" => "AWS $accesskey:$sig");

print $res->status_line, "\n", $res->content;

Here's perl:

use warnings;
use strict;
use HTTP::Date;
use Digest::SHA qw(hmac_sha1);
use LWP::UserAgent;
use MIME::Base64;
use Encode qw(encode_utf8);

@ARGV == 4 || die "usage: $0 url distribution_id accesskey secretkey\n";

my $invalid_url = $ARGV[0];
my $distribution_id = $ARGV[1];
my $accesskey = $ARGV[2];
my $secretkey = $ARGV[3];

my $url = "https://cloudfront.amazonaws.com/2010-11-01/distribution/$distribution_id/invalidation";
my $date = time2str;

my $post_data = <<HERE;
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch>
  <Path>$invalid_url</Path>
  <CallerReference>$date</CallerReference>
</InvalidationBatch>
HERE

my $sig = encode_base64(hmac_sha1(encode_utf8($date),encode_utf8($secretkey)));

my $browser = LWP::UserAgent->new;
my $res = $browser->post($url,
                         "Content" => $post_data,
                         "ContentType" => "text/xml",
                         "x-amz-date" => $date,
                         "Authorization" => "AWS $accesskey:$sig");

print $res->status_line, "\n", $res->content;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文