Saturday, March 3, 2012

How to check url is still alive in asp.net

When I develop the web directory "iblogseeker.com", I need to check blog url user input. I found out the best way to detect whether a blog is alive or not, since blog url is very important and sensitive in this case. This example show detecting url on web using System.Net.HttpWebRequest and HttpWebRequest, and ValidatorCallout and RegularExpressionValidator for validating client side user input.

ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an TextBox "txtUrl" and a validator control "RegularExpressionValidator1" as you normally do. Then add the ValidatorCallout "ValidatorCalloutExtender1" and set its TargetControlID property to reference the validator control.

Validating Url with ASP.Net

Add the following code to <form> tag.
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:Label ID="Label2" runat="server" Text="URL :"></asp:Label><br/>
        <asp:TextBox ID="txtUrl" runat="server" Width="250px" MaxLength="200">http://www.iblogseeker.com</asp:TextBox>
        <asp:Button ID="button1" runat="server" Text="Go" onclick="button1_Click" />
        <br />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="txtUrl"
            ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?"
            Display="None"
            ErrorMessage="<b>Url is not well-formatted.</b><br />
            <div style='margin-top:5px;padding:5px;border:1px solid #e9e9e9;background-color:white;'>
            <b>e.g.&nbsp;</b>
            <a href='javascript:window.open(&quot;http://www.aspmemo.net&quot;);'>http://www.aspmemo.net</a></div>">
            </asp:RegularExpressionValidator>
        <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender1"
            runat="server" Enabled="True" TargetControlID="RegularExpressionValidator1"></asp:ValidatorCalloutExtender>
        <br />
        <asp:Label ID="lblUrlMsg" runat="server"></asp:Label>
    </div>
</form>


In code-behind, button click event look like as below.

protected void button1_Click(object sender, EventArgs e)
{
    try
    {
        string url = txtUrl.Text;
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.AllowAutoRedirect = false;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            string msg = string.Empty;
            switch (response.StatusCode)
            {
                case HttpStatusCode.OK: //HTTP status 200
                    msg = HttpStatusCode.OK.ToString();
                    break;
                case HttpStatusCode.NoContent: //HTTP status 204
                    msg = HttpStatusCode.NoContent.ToString();
                    break;
                case HttpStatusCode.NotFound: //HTTP status 404
                    msg = HttpStatusCode.NotFound.ToString();
                    break;
                case HttpStatusCode.RequestTimeout: //HTTP status 408
                    msg = HttpStatusCode.RequestTimeout.ToString();
                    break;
                case HttpStatusCode.ServiceUnavailable: //HTTP status 503
                    msg = HttpStatusCode.ServiceUnavailable.ToString();
                    break;
                case HttpStatusCode.Unauthorized: //HTTP status 401
                    msg = HttpStatusCode.Unauthorized.ToString();
                    break;
                case HttpStatusCode.MovedPermanently: //HTTP status 301
                    msg = HttpStatusCode.MovedPermanently.ToString();
                    break;
                case HttpStatusCode.BadRequest: //HTTP status 400
                    msg = HttpStatusCode.BadRequest.ToString();
                    break;
                default:
                    msg = "Invalid URL!";
                    break;
            }
            lblUrlMsg.Text = msg;
        }
    }
    catch (Exception ex)
    {
        lblUrlMsg.Text = "Invalid URL!";
    }
}

Whenever you type not-well-formatted url (including special character), it show message. if you put well-formatted url, it show HttpStatus of url.

HttpStatusCode : http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx

ValidatorCallout Demonstration : http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ValidatorCallout/ValidatorCallout.aspx

No comments:

Post a Comment