Quantcast
Viewing all articles
Browse latest Browse all 10

A VB.net Example showing how to create a time limited URL to access an Azure Blob

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.

    <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

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles