pr0g33k

Encode/Decode a URL for use as a Route Parameter

I've been working on integrating this blog with Microsoft's Azure Blob Storage. I'll have more posts on how to set it up in a few days. In the mean time, I found a nice, little gem I thought I'd share.

I have a page in the admin section of this blog with a controller and views for file management (List.cshtml, Upload.cshtml, Edit.cshtml, etc.). In the List.cshtml view, I have an unordered list driven by an IEnumerable<IListBlobItem> queried from the Azure CloudBlobContainer. For each URI in IListBlobItem, I create an ActionLink that navigates to Edit.cshtml. I needed to pass the URI as a RouteValue, though, and I was pretty sure that the following wouldn't work very well: http://localhost:1111/FileManager/Edit/http://localhost:10000/images/my-uploaded-image.jpg

HttpServerUtility.UrlTokenEncode(Byte[] input) & HttpServerUtility.UrlTokenDecode(String input) to the Rescue!

@Html.ActionLink(Path.GetFileName(url), "Edit", new { id = HttpServerUtility.UrlTokenEncode(System.Text.UTF8Encoding.ASCII.GetBytes(url)) }, new { data_href = url })

That creates a link that renders like this:

<a data-href="http://127.0.0.1:10000/devstoreaccount1/images/my-uploaded-image.jpg" href="/Admin/FileManager/Edit/aHR0cDovLzEyNy4wLjAuMToxMDAwMC9kZXZzdG9yZWFjY291bnQxL2ltYWdlcy8xcXZnZnV5bmJrYW1xZ2F6M2pkaTZ3Mi5qcGc1">my-uploaded-image.jpg</a>

In the FileManager controller, the Edit method accepts the id RouteParameter and decodes the value:

public ActionResult Edit(String id)
{
    ViewBag.Url = UTF8Encoding.ASCII.GetString(HttpServerUtility.UrlTokenDecode(id));
    return View();
}

The "data-href" attribute is used by a jQuery script that opens a preview popup if the file is an image. I'll cover that in a future post.

Posted on 4/25/2013 at 02:04 PM , Edited on 4/25/2013 at 08:04 PM
Tags: C#MVC

Comments:

Leave a comment
  1. CAPTCHA