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.
- File --> New --> Project
- Select ASP.NET Web Application
- Set name and location
- 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.
- <div class="jumbotron">
- <h1>URL Shortner</h1>
- </div>
- @if (!string.IsNullOrEmpty(ViewBag.ShortenedUrl))
- {
- <span>Short Url is: </span> <a href="@ViewBag.ShortenedUrl" target="_blank">@ViewBag.ShortenedUrl</a>
- }
- <div class="row">
- <div class="col-md-4">
- @using (Html.BeginForm("Index", "Home", FormMethod.Post))
- {
- <input type="text" name="longUrl" />
- <input type="submit" value="Get Short Url" />
- }
- </div>
- <div class="col-md-4">
-
- </div>
- <div class="col-md-4">
-
- </div>
- </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,
- using System;
- using System.Web.Mvc;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web.Script.Serialization;
- using UrlShortner.Models;
Globally declare the string type variable API_KEY.
-
- 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.
- [HttpPost]
- public ActionResult Index(FormCollection form)
- {
- string longUrl = Convert.ToString(form["longUrl"]);
- var shortenedResponse = Shorten(longUrl);
-
- ViewBag.ShortenedUrl = shortenedResponse.id;
- return View();
- }
-
- public static ShortenLongUrlResponse Shorten(string longUrl)
- {
- if (string.IsNullOrWhiteSpace(longUrl))
- throw new ArgumentException("You must provide a value for longUrl");
-
- var req = WebRequest.Create(GetUrl());
- req.Method = "POST";
- req.ContentType = "application/json";
-
- var postBody = string.Format(@"{{""longUrl"": ""{0}""}}", longUrl);
- var postData = Encoding.ASCII.GetBytes(postBody);
-
- req.ContentLength = postData.Length;
- var reqStream = req.GetRequestStream();
- reqStream.Write(postData, 0, postData.Length);
- reqStream.Close();
-
-
- var resp = req.GetResponse();
- using (var respReader = new StreamReader(resp.GetResponseStream()))
- {
- var responseBody = respReader.ReadToEnd();
-
- var deserializer = new JavaScriptSerializer();
- return deserializer.Deserialize<ShortenLongUrlResponse>(responseBody);
- }
- }
-
- protected static string GetUrl()
- {
- const string API_URL = "https://www.googleapis.com/urlshortener/v1/url";
-
- if (string.IsNullOrWhiteSpace(API_KEY))
- return API_URL;
- else
- return string.Concat(API_URL, "?key=", API_KEY);
- }
-
-
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.
- {
- "kind": "urlshortener#url",
- "id": "https://goo.gl/H059",
- "longUrl": "http://www.yahoomail.com/"
- }
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.
- public class ShortenLongUrlResponse
- {
- public string kind { get; set; }
- public string id { get; set; }
- public string longUrl { get; set; }
- }
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.