ASP.NET MVC - Google URL Shortener

Introduction

Here, we are going to build an ASP.NET MVC application that will get a URL (e.g. www.yahoomail.com) from a textbox and send it to the controller which will further shorten the URL using Google URL Shortener API.

Body

First of all, log in to Gmail with your account and pasts the URL in the address bar here. Here, you will get your Google URL Shortener API key. Then, create a new ASP.NET MVC application. 
  1. File --> New --> Project 
  2. Select ASP.NET Web Application
  3. Set name and location
  4. On the next screen, select Web Application, select MVC Template with "No Authentication", and click OK.
In Views/Home/Index.cshtml, we modify it with some code.
  1. <div class="jumbotron">  
  2.     <h1>URL Shortner</h1>  
  3. </div>  
  4. @if (!string.IsNullOrEmpty(ViewBag.ShortenedUrl))  
  5. {  
  6.    <span>Short Url is: </span> <a href="@ViewBag.ShortenedUrl" target="_blank">@ViewBag.ShortenedUrl</a>  
  7. }  
  8. <div class="row">  
  9.     <div class="col-md-4">  
  10.       @using (Html.BeginForm("Index""Home", FormMethod.Post))  
  11.       {  
  12.         <input type="text" name="longUrl" />  
  13.         <input type="submit" value="Get Short Url" />  
  14.       }  
  15.     </div>  
  16.     <div class="col-md-4">  
  17.          
  18.     </div>  
  19.     <div class="col-md-4">  
  20.          
  21.     </div>  
  22. </div>  

A text box, that will ask for the long URL and a Submit button are created using the above code. After submission and load back, we will check for null result that is actually in ViewBag. If result is not null or empty then we will show it as a link.

And here is the controller logic.

Add necessary using, 
  1. using System;  
  2. using System.Web.Mvc;  
  3. using System.IO;  
  4. using System.Net;  
  5. using System.Text;  
  6. using System.Web.Script.Serialization;  
  7. using UrlShortner.Models;  
Globally declare the string type variable API_KEY.
  1. // Enter your Google URL Shortener API key here  
  2.         const string API_KEY = "Past your google url shortener api key here";  
And logic for Post Action method is given below, where we get the longUrl from form collection and shorten it and return the result using ViewBag to the Index View. 
  1. [HttpPost]  
  2.         public ActionResult Index(FormCollection form)  
  3.         {  
  4.             string longUrl = Convert.ToString(form["longUrl"]);  
  5.             var shortenedResponse = Shorten(longUrl);  
  6.   
  7.             ViewBag.ShortenedUrl = shortenedResponse.id;  
  8.             return View();  
  9.         }  
  10.   
  11.         public static ShortenLongUrlResponse Shorten(string longUrl)  
  12.         {  
  13.             if (string.IsNullOrWhiteSpace(longUrl))  
  14.                 throw new ArgumentException("You must provide a value for longUrl");  
  15.   
  16.             var req = WebRequest.Create(GetUrl());  
  17.             req.Method = "POST";  
  18.             req.ContentType = "application/json";  
  19.   
  20.             var postBody = string.Format(@"{{""longUrl"": ""{0}""}}", longUrl);  
  21.             var postData = Encoding.ASCII.GetBytes(postBody);  
  22.   
  23.             req.ContentLength = postData.Length;  
  24.             var reqStream = req.GetRequestStream();  
  25.             reqStream.Write(postData, 0, postData.Length);  
  26.             reqStream.Close();  
  27.   
  28.   
  29.             var resp = req.GetResponse();  
  30.             using (var respReader = new StreamReader(resp.GetResponseStream()))  
  31.             {  
  32.                 var responseBody = respReader.ReadToEnd();  
  33.   
  34.                 var deserializer = new JavaScriptSerializer();  
  35.                 return deserializer.Deserialize<ShortenLongUrlResponse>(responseBody);  
  36.             }  
  37.         }  
  38.   
  39.         protected static string GetUrl()  
  40.         {  
  41.             const string API_URL = "https://www.googleapis.com/urlshortener/v1/url";  
  42.   
  43.             if (string.IsNullOrWhiteSpace(API_KEY))  
  44.                 return API_URL;  
  45.             else  
  46.                 return string.Concat(API_URL, "?key=", API_KEY);  
  47.         }  
  48.   
  49.           
The Shorten() method will accept a string URL and concatenate our API key to Google Shortener API (https://www.googleapis.com/urlshortener/v1/url) and send a web request. As a result, a JSON serialized response returns as given below.
  1. {  
  2.  "kind""urlshortener#url",  
  3.  "id""https://goo.gl/H059",  
  4.  "longUrl""http://www.yahoomail.com/"  
  5. }  
It will de-serialize it and convert it to ShortenLongUrlResponse type object using JavaScriptSerializer. Description of ShortenLongUrlResponse.cs class in Models folder is as follows.
  1. public class ShortenLongUrlResponse  
  2.     {  
  3.         public string kind { get; set; }  
  4.         public string id { get; set; }  
  5.         public string longUrl { get; set; }  
  6.     }  
Conclusion
We can use short URLs in our applications for sending these in emails, SMS, as well as to show on the pages.

Please download the attached source code file, extract it, and just copy and post all folders to the root of the application.