tags:

views:

303

answers:

1

I have the following code which will ping a typical anonymous website without a problem but I receive either an unauthorized error or forbidden. Here is the code that's giving me the forbidden error.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;

public partial class Ping : System.Web.UI.Page
{
    protected string PingResponseTime(string url)
    {
        // Create a 'WebRequest' object with the specified url. 
        WebRequest myWebRequest = WebRequest.Create(url);
    myWebRequest.Credentials = new NetworkCredential("username","password","domain");
        myWebRequest.Timeout = 90000;
        string requestTime, elapsedSecs;
        // If trace enabled - set the Trace
        WebHeaderCollection myWebCollection = new WebHeaderCollection();
        myWebCollection.Add("Trace", "1");
        myWebRequest.Headers = myWebCollection;
        // Send the 'WebRequest' and wait for response. 
        DateTime startTime = DateTime.Now;       // Start time
        myWebRequest.GetResponse();              // Web Request
        DateTime stopTime = DateTime.Now;        // End Time
        TimeSpan duration = stopTime - startTime;     // Time Diff
    //    succededStr = "1";
        requestTime = startTime.ToString();
        elapsedSecs = duration.ToString().Substring(6);
        return elapsedSecs;
    }

    protected void btnPing_Click(object sender, EventArgs e)
    {
        lblResponseTime.Text = PingResponseTime(txtURL.Text.ToString());
    }
}

What am I doing wrong that I'm getting the forbidden error when pinging a Sharepoint site? I've even tried a Sharepoint site with anonymous access enabled.

+1  A: 

Have you tried replacing the line :

myWebRequest.Credentials = new NetworkCredential("username", "password", "domain");

with :

myWebRequest.Credentials = CredentialCache.DefaultCredentials;

or :

myWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
mathieu