Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Http Header for Amazon S3 programmatically?

Tags:

c#

.net

amazon-s3

I want to set expiration date header for files which are stored in S3 by my asp.net web application.

  • first case - during PutObject requests
  • second case - update of expiration date once a month to update expiration dates.
like image 963
st78 Avatar asked Apr 03 '11 22:04

st78


1 Answers

As you are using Asp.net, I assume you are using the AWS .NET SDK.

To add the Expires(or any other http header) when uploading the object, add it as part of the PutObject request.

var client = new Amazon.S3.AmazonS3Client(AWS_Key, AWS_SecretKey);

var req = new Amazon.S3.Model.PutObjectRequest()
                 .WithFilePath(@"C:\myfile.txt")
                 .WithKey("myfile.txt")
                 .WithBucketName("mybucket");

req.AddHeader("expires", "Thu, 01 Dec 1994 16:00:00 GMT");

client.PutObject(req);

To change the header on an existing object, you need to copy the object to itself.

var req = new Amazon.S3.Model.CopyObjectRequest()
                 .WithDirective(Amazon.S3.Model.S3MetadataDirective.REPLACE)
                 .WithSourceBucket("mybucket")
                 .WithSourceKey("myfile.txt")
                 .WithDestinationBucket("mybucket")
                 .WithDestinationKey("myfile.txt");

req.AddHeader("expires", "Thu, 01 Dec 1994 16:00:00 GMT");

client.CopyObject(req);

Note: .WithDirective(Amazon.S3.Model.S3MetadataDirective.REPLACE) must be set in order to specify new headers. Otherwise the existing headers are just copied over.

More more info see the .NET SDK docs.

like image 153
Geoff Appleford Avatar answered Sep 28 '22 02:09

Geoff Appleford