Thursday, September 09, 2010

How to remove external links from a asp.net web page

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        public string RootUrl
        {
            get
            {
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.Scheme,
                    Uri.SchemeDelimiter,
                    requestUri.Host,
                    requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port),
                    request.ApplicationPath);
                return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl);
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
            base.Render(htw);
            string html = sb.ToString();
 
            string tag = "a";
 
            List<string> tags = new List<string>();
            int limit = 0, lb = 0, ub = 0;
            string startTag = string.Format("<{0}", tag);
            string endTag = string.Format(">", tag);
            string lHtml = html.ToLower();
            do
            {
                lb = lHtml.IndexOf(startTag, limit);
                if (lb > 0)
                {
                    limit = ub = lHtml.IndexOf(endTag, lb) + endTag.Length;
                    tags.Add(html.Substring(lb, ub - lb));
                }
                else limit = lb;
            }
            while (limit > 0);
            foreach (string a in tags)
            {
                string link = a.ToLower();
                link = link.Replace("'""\"");
                lb = link.IndexOf("href");
                lb = link.IndexOf("\"", lb);
                ub = link.IndexOf("\"", lb + 1);
                string href = link.Substring(lb + 1, ub - (lb + 1));
                if (href.StartsWith("http://") && !href.StartsWith(this.RootUrl.ToLower()))
                {
                    link = link.Replace(href, string.Format("{0}StopUrl.aspx"this.RootUrl));
                    html = html.Replace(a, link);
                }
            }
            writer.Write(html);
        }
     
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <a href="About.aspx">About</a>
        <a href="Default.aspx">Home</a>
        <a href="http://www.yahoo.com">Yhaoo</a>
        <a href="http://localhost/ActiveTest/Test.aspx">Test Page</a>
    </div>
    </form>
</body>
</html>

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...