c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
API

How to implement URL shortener google API in asp.net application?

| | MVC

The google URL shortener allows you to make URL shortened which will expand, when the user access on it, will get a full original URL form. Normally it is suitable for sharing your articles or image URL path over social websites like google plus, Facebook, Twitter etc.
you can get same facility by manually from this link https://goo.gl/

   

I have entered URL www.infinetsoft.com  it gives the new URL shortener is goo.gl/5a9uwo . You can check the new URL where it is redirecting.

Here I will show you how to develop an asp.net mvc application using google URL shortener API. This link will guides you how to register the Google URL shortener API in the google Developers console. It will provide the ClientID and google URL shortener API key.  You can replace the key in the GetShortURL () method API_Key.  To use API service you should enable the URL SHortener API like this,

Step 1Create an asp.net mvc project and right click on the controller folder and create a new controller and name it as HomeController. Inside the homeController copy and paste the following code.

public ActionResult Index()
        {
           return View();
        }
[HttpPost]
        public JsonResult GetShortURL(string oldurl)
        {
            WebRequest request = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=API_key");
            request.Method = "POST";
            request.ContentType = "application/json";
            string requestData = string.Format(@"{{""longUrl"":""{0}""}}",oldurl);
            byte[] requestRawData = Encoding.ASCII.GetBytes(requestData);
            request.ContentLength =requestRawData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestRawData,0, requestRawData.Length);
            requestStream.Close();
            WebResponse response = request.GetResponse();
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();
 
            var deserializer = new JavaScriptSerializer();
            var results = deserializer.Deserialize<GoogleResponse>(responseData);
            return Json(results.Id);
        }

        public class GoogleResponse
        {
            public string Id { get; set; }
            public string OldUrl { get; set; }

        }

Step 2: Right click on the Share folder and create a view named as error. Copy and paste the following code.

@{
    Layout = null;
}
 
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>short your url</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
 
            $("#btnGenerate").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/GetShortURL",
                    contentType: "application/json;charset=utf-8",
                   dataType: "json",
                    data: '{ "oldurl" : "' + $("#txtOldurl").val() + '" }',
                    success: function (results) {
                        $("#txtNewurl").val(results);
                    },
                    error: function (err) {
                        alert(err.status + " - " +err.statusText);
                    }
                });
            });
 
        });
 
 
    </script>
 
</head>
<body style="border: 1px solid #DED8D8; width: 500px; height: 305px; font-family: Arial;">
    <div>
        <h2>short your url</h2>
        <span>Enter Long URL :</span>
        <br />
        <br />
        <input type="text" id="txtOldurl" size="60" />
        <br />
        <br />
        <input type="button" id="btnGenerate" value="Get Short URL" />
        <br />
        <br />
        <input type="text" id="txtNewurl" readonly="readonly" size="60" />
    
    </div>
</body>
</html> 

Description: It contains two textboxes and a Get Short URL button. The first textbox accepts the URL text. Click on the button, Ajax jQuery function calls the server side GetShortURL method. It deserializes and returns the JSON response as string URL to the caller.