如何模拟外联网的Web请求? (C#)

时间:2018-02-24 18:46:08

标签: c# testing automation

我正在进行测试,以验证我们面向公众的网站是否正常运营。为此,我运行了一段代码来制作HttpWebRequest。如何模拟组织内部网外的用户?有没有办法在州的另一边指定用户?我会在标题中添加额外的信息吗?

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);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

我会使用Selenium编写自动化测试。 John Sonmez在Pluralsight上有一个很好的入门课程。或者,您可以启动here