Using the Google URL Shortener API with ASP.NET MVC 3 and C#

Post to Twitter

I recently showed how to use the Google URL Shortener API with PHP. Today I’ll switch gears in regards to the technology used and instead of PHP I’ll use ASP.NET MVC 3 and C#.


According to the documentation we can send a WebRequest that includes this:

POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json
 
{"longUrl": "http://www.insert-your-url-here.com/"}

Creating a new ASP.NET MVC 3 project in Visual Studio I added a HomeController with the following code:

namespace MvcGoogleUrl.Controllers
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult ShortenURL(string longurl)
		{
			return View();
		}
	}
}

From there added two Views: Index.cshtml and ShortenURL.cshtml

Here are the contents of Index.cshtml:

@{
    ViewBag.Title = "Index";
}

<p>Enter a URL to shorten</p>
@using(Html.BeginForm("ShortenURL", "Home", FormMethod.Post)) {
	@Html.Label("URL: ")
	@Html.TextBox("longurl", "", new { @maxlength = "255" })
	<input type="submit" value="Submit" />
}

Here are the contents of ShortenURL.cshtml:

@{
    ViewBag.Title = "ShortenURL";
}

<p>Result:</p>
@ViewBag.ShortenedUrl

Nothing fancy, just enough to enter in a long URL and get some results back.

I then added two classes to the HomeController called: GoogleShortenedURLResponse and GoogleShortenedURLRequest. Yeah, not the best names but it works. These are the classes that I’ll use to work with the JSON Google requires and passes back.

Note: Keep in mind this article is about trying to keep things simple, in a production web app you don’t necessarily want to structure your classes like this or even parse your JSON like this – its up to you to change it to meet your needs, etc.

Here is the code for the two new classes:

private class GoogleShortenedURLResponse
{
	public string id { get; set; }
	public string kind { get; set; }
	public string longUrl { get; set; }
}

private class GoogleShortenedURLRequest
{
	public string longUrl { get; set; }
}

So the actual HomeController now looks like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;


namespace MvcGoogleUrl.Controllers
{
    public class HomeController : Controller
    {
		private class GoogleShortenedURLResponse
		{
			public string id { get; set; }
			public string kind { get; set; }
			public string longUrl { get; set; }
		}

		private class GoogleShortenedURLRequest
		{
			public string longUrl { get; set; }
		}
		
		public ActionResult Index()
        {
            return View();
        }

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult ShortenURL(string longurl)
		{
			string googReturnedJson = string.Empty;
			JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();

			GoogleShortenedURLRequest googSentJson = new GoogleShortenedURLRequest();
			googSentJson.longUrl = longurl;
			string jsonData = javascriptSerializer.Serialize(googSentJson);
			
			byte[] bytebuffer = Encoding.UTF8.GetBytes(jsonData);

			WebRequest webreq = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
			webreq.Method = WebRequestMethods.Http.Post;
			webreq.ContentLength = bytebuffer.Length;
			webreq.ContentType = "application/json";			

			using (Stream stream = webreq.GetRequestStream())
			{
				stream.Write(bytebuffer, 0, bytebuffer.Length);
				stream.Close();
			}

			using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
			{
				using (Stream dataStream = webresp.GetResponseStream())
				{
					using (StreamReader reader = new StreamReader(dataStream))
					{
						googReturnedJson = reader.ReadToEnd();
					}
				}
			}

			GoogleShortenedURLResponse googUrl = javascriptSerializer.Deserialize<GoogleShortenedURLResponse>(googReturnedJson);
			
			ViewBag.ShortenedUrl = googUrl.id;
			return View();
		}
    }
}

The real magic happens in the ShortenURL method as you can see. Also you will note I made a reference to the System.Web.Extensions assembly for the JSON support. The long URL you want to shorten is passed in and the WebRequest is fired off to Google’s API. The result comes back as JSON and is converted into an object where we can easily extract the id value which is where Google sticks the newly shortened URL.

Note: If you do plan to make heavy use of the Google URL Shortener API then keep in mind you need to get an API key, this will allow you to call this API much more frequently than as anonymous. Once you have your API key from Google you can just tack it on the end of the query string like so:


https://www.googleapis.com/urlshortener/v1/url?key=<your_key>

So its a little more work than doing the same thing in PHP, but the end result is just the same.

Post to Twitter

This entry was posted in ASP.NET, C#. Bookmark the permalink.

One Response to Using the Google URL Shortener API with ASP.NET MVC 3 and C#

  1. Suresh says:

    Very nice code…Clarified lot of things..

    In this case, response structure is simple:

    private class GoogleShortenedURLResponse
    {
    public string id { get; set; }
    public string kind { get; set; }
    public string longUrl { get; set; }
    }

    I followed the same approach for Google Distance Matrix API…But I do not know how to define the response structure…Do you have any idea?

Comments are closed.