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
asp.net MVC

How to extract favicon from a webpage URL?

| | ASP-NET , JavaScript , MVC

In this article, I will show you how to extract favicon from a web page using webpage URL. When you pass URL of web page to the function and it will result the icon of the website.

 

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. 

Home controller:

public JsonResult GetFavicon(string url)
        {
            string htmlCode;
            string faviconurl="";
            using (WebClient client = new WebClient())
            {
                htmlCode= client.DownloadString(url);
            }
            HtmlDocument doc = new HtmlDocument();
           doc.LoadHtml(htmlCode);
           if (doc.DocumentNode != null)
            {
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes(@"//link[@href]"))
               {
 
                   HtmlAttribute att = link.Attributes["href"];
                   if (att.Value.EndsWith(".ico"))
                   {
                       faviconurl = att.Value;
                   }
               }
            }
            return Json(faviconurl, JsonRequestBehavior.AllowGet);
}

Step 2: Right click on the index method and create a razor view and name it as index. Copy and paste the following code. 

View.cstml:

$.ajax({
               type: "POST",
               url: '@Url.Action("GetFavicon", "Home", new { area = "" })',
               contentType: "application/json;charset=utf-8",
               data: "{'url': " +JSON.stringify($("#txtUrl").val()) + "}",
               datatype: "JSON",
               success: function (response) {
                   $("#favIcon").attr("src", response);
               }
            });