samedi 24 février 2018

How do I simulate a web request from an extranet? (C#)

I am working on tests that verify that our public-facing websites are operational. To do that, I have a piece of code I run to make an HttpWebRequest. How do I simulate being a user outside the intranet of the organization? Is there a way I can specify a user on the other side of the state? Would I add extra information to the header?

private async Task RunURLRequestAsync(string input)
    {
        string methodName = Utils.getCurrentMethod();
        Log("In:  " + methodName);
        try
        {
            var client = new HttpClient();
            var uri = new Uri(input);
            Log("URI is " + uri.ToString());
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(uri);
            webrequest.CookieContainer = new CookieContainer();
            webrequest.Method = "GET";
            webrequest.Timeout = 2000;
            HttpWebResponse response = (HttpWebResponse) webrequest.GetResponse();
            pageStatusCode = response.StatusCode.ToString();
            pageStatusDescription = response.StatusDescription.ToString();
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                pageStatusCode = "401 Unauthorized";
            }
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream);
                string result = reader.ReadToEnd();
                Log("Web Page Contents: " + result);

            }
        }
        catch(Exception exc)
        {
            if(exc.Message.Contains("Unauthorized"))
            {
                pageStatusCode = "401";
                pageStatusDescription = "Unauthorized (Expected)";
                return;
            }
            else
            {
                Log(exc.Message);
                Log(exc.StackTrace);
            }
        }

     }

Aucun commentaire:

Enregistrer un commentaire