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.
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,
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;
- // Enter your Google URL Shortener API key here
- 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);
- }
- {
- "kind": "urlshortener#url",
- "id": "https://goo.gl/H059",
- "longUrl": "http://www.yahoomail.com/"
- }
- public class ShortenLongUrlResponse
- {
- public string kind { get; set; }
- public string id { get; set; }
- public string longUrl { get; set; }
- }
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.

Pratik PimplePosted Jan 5, 2020, 11:45 AM
While using your code throws below error: An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code Additional information: The remote server returned an error: (404) Not Found.
Rathrola Prem KumarPosted Nov 18, 2019, 6:54 PM
Hi all,As of March 30, 2019, the goo.gl URL shortener was shut down. Please see this blog post for alternatives. https://developers.googleblog.com/2018/03/transitioning-google-url-shortener.html
Raviteja SridasyamPosted Nov 10, 2019, 11:49 PM
Iam facing issue at var resp = req.GetResponse(); System.Net.WebException: 'The remote server returned an error: (404) Not Found.' please help
Raviteja SridasyamPosted Nov 10, 2019, 7:48 PM
Can you please upload complete project I am bit confused please try to upload the full project file
Sourabh DhimanPosted Jun 28, 2019, 1:04 AM
{ "kind": "urlshortener#url", "id": "https://goo.gl/H059", "longUrl": "http://www.yahoomail.com/" } what is use this
Varikuti JayanthiPosted May 16, 2019, 7:55 AM
If getresponse() method is showing 400 error. (HttpWebRequest-The remote server returned an error: (400) Bad Request) what should we do?
Rushi MehtaPosted Jan 18, 2018, 5:39 AM
Along wit the code i want snap of all the process oyu are doing, because through code it gets difficult to understand
Rushi MehtaPosted Jan 17, 2018, 3:54 AM
Can you share the snapshot of above the blogs which you have posted