Use of HttpWebResponse in windows Services and Console Applications

Links to the original text: http://www.cnblogs.com/greatwang/archive/2012/10/16/3292548.html

HttpWebRequest+HttpWebResponse is often used in console applications, such as checking whether pages are normal or accessed regularly. As requirements change, we may need to migrate this functionality to windows services for execution. windows services will not be easily shut down by mistake.

1. Use HttpWebResponse in console applications:


HttpWebRequest request = WebRequest.Create(urlPath) as HttpWebRequest;

//As with the following three lines, if all of them are commented, you will see the exception information of 401.
request.UseDefaultCredentials = true;              
//request.Credentials = CredentialCache.DefaultNetworkCredentials;
//request.Credentials = CredentialCache.DefaultCredentials;

// Get the response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
        // Display the status.
        WriteLog(response.StatusDescription);
        // Get the stream containing content returned by the server.
        using (Stream dataStream = response.GetResponseStream())
        {
            // Open the stream using a StreamReader for easy access.
            using (StreamReader reader = new StreamReader(dataStream))
            {
                //Read the content.
                string responseFromServer = reader.ReadToEnd();
                //Display the content.
                Console.WriteLine(responseFromServer);
                Console.WriteLine(DateTime.Now.ToString() + " Successed.");
                WriteLog("Successed");
            }
        }
    }
    else
    {
        WriteLog("status code is not Ok it was" + response.StatusCode.ToString());
    }
}

  CONCLUSION: The above code works well becauseThe console application is based on the current logged-in user identityVisit.
2. Using HttpWebResponse in windows Services
We migrate the above code directly to windows service, which can work normally in theory. But the actual situation has the following mistakes:


System.Net.WebException: The remote server returned an error: (401) Unauthorized.
In System.Net.HttpWebRequest.GetResponse()


So, how can we solve it? We use the local IIS site. First quote a passage from a netizen:


Windows Service application run under the LocalSystem account by default, whereas your console app runs under your user account, you may therefore be meeting permission problems (windows firewall?)

You should run the service under the administrator account to see if this resolves your issue.

Just imagine, it's not hard to understand that windows service programs run on local system accounts.  
In fact, the key part is to set up UseDefault Credentials or Credentials, and the three methods in the code are effective. The differences among the three methods are as follows:


1. Credentials = CredentialCache.DefaultCredentials; indicates that the current user's authentication credentials will be brought with the request.
2. UseDefaultCredentials = true; this method calls the previous method internally, so it is the same as the previous method.
3. Credentials = CredentialCache. Default Network Credentials; a new method referenced in. NET 2.0.


Solution 1: Modify the credential format, specify user name and password:


request.UseDefaultCredentials = true;

Amend as follows:

NetworkCredential credentials = new NetworkCredential("username", "pwd");

request.Credentials = credentials;



Reprinted at: https://www.cnblogs.com/greatwang/archive/2012/10/16/3292548.html

Tags: Windows IIS firewall network

Posted on Fri, 09 Aug 2019 05:33:28 -0700 by mark_18