How to set Http Header for Amazon S3 programmatically?
For AWSSDK.S3 V3.* its works like this:
request.Headers.Expires = DateTime.Now.AddMinutes(2);
If you are using the AWS SDK 2.X then the "AddHeader" method is no longer available. To add a header you just modify the header collection directly.
req.Headers["expires"] = "Thu, 01 Dec 1994 16:00:00 GMT";
Here is the modified example Geoff used above:
var client = new Amazon.S3.AmazonS3Client(AWS_Key, AWS_SecretKey);
var req = PutObjectRequest req= new PutObjectRequest()
{
BucketName = "mybucket",
Key = "myfile.txt",
FilePath = @"C:\myfile.txt"
};
req.Headers["expires"] = "Thu, 01 Dec 1994 16:00:00 GMT";
client.PutObject(req);
To change the header it's the same way:
var req = new Amazon.S3.Model.CopyObjectRequest()
{
MetadataDirective = S3MetadataDirective.REPLACE,
SourceBucket = "mybucket",
SourceKey = "myfile.txt",
DestinationBucket = "mybucket",
DestinationKey = "myfile.txt"
};
req.Headers["expires"] = "Thu, 01 Dec 1994 16:00:00 GMT";
client.CopyObject(req);
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.