I needed to set up a quick download service for a file stored in
Azure Blob Storage. As all examples for this were in C# I thought I’d
post a VB.net example for anyone that needed it. The code is documented
in the comments. The example also shows sending a HTML email with the
URL embedded inside it.
Below is the MVC controller method which generates the URL and sends the email.
Below is the MVC controller method which generates the URL and sends the email.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| <HttpPost()> Function RequestDownload(model As DownloadRequest) As ActionResult ' Get the storage account details from the configuration file. Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings( "BlobStorageConnectionString" ).ConnectionString) ' Create the container reference object Dim container As CloudBlobContainer = storageAccount.CreateCloudBlobClient().GetContainerReference( "downloads" ) ' Create the blob reference object Dim blob = container.GetBlobReference(model.Filename) ' Calculate the time two minutes from now. Dim exTime As DateTime = DateTime.UtcNow + TimeSpan.FromMinutes(2) ' Now create a new shared access signature that expires two minutes ' from creation with Read only permissions. Dim sas = blob.GetSharedAccessSignature( New SharedAccessPolicy() With { .Permissions = SharedAccessPermissions.Read, .SharedAccessExpiryTime = exTime }) ' Now create the URL Dim sasURL = blob.Uri.AbsoluteUri & sas ' Generate an email. ' Create the smtp object. Dim client As New SmtpClient( "my.smtp.server" ) ' Now generate a new email message Dim message As New MailMessage message.From = New MailAddress( "me@nobody.here.com" ) message. To .Add( New MailAddress(model.ToAddress)) message.Subject = "Download link for " & model.Filename ' Make the html body of the email. message.IsBodyHtml = True Dim body = <Html> <p>Click the below link to download <b><%= model.Filename %></b></p> <p>This link will only be valid for two minutes from issue.</p> <a href=<%= sasURL %>><%= sasURL %></a> <p style= "color: red;" > Do not share this email link.</p> <p>Regards</p> <P>The Team</P> </Html> message.Body = body.ToString ' Now send. client.Send(message) Return RedirectToAction( "Index" ) End Function |
Sign up here with your email
ConversionConversion EmoticonEmoticon