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

I am trying to run following code it works fine when runs on localhost IIS but returns error when hosted on my web server IIS

Error : -- The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() at _Default.btnsubmit_Click(Object sender, EventArgs e) in e:\WebSite1\Default.aspx.cs:

try
{

var webAddr = "http://serviceserver/someService";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.ContentLength = 0;
httpWebRequest.Method = "GET";

httpWebRequest.Credentials = new NetworkCredential("user", "password");
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new treamReader(httpResponse.GetResponseStream()))
   {
       var result = streamReader.ReadToEnd();
       Label1.Text = result;
   }
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.StackTrace);
Response.Write(ex.InnerException);
}

Update The above service URL is WCF service and it is secured via transport credentials in windows I am trying to hit this URL via my web application and passing my credentials as Network Credentials. When I run this web application on my local machine it runs fine and returns the required data. But when I host this application I got above stated error. Am I doing something wrong.



Solution 1:[1]

You need to look on your server for a username, pass, and if it is basic or digest. I set my command up like this:

 HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
 var cache = new CredentialCache();
 cache.Add(new Uri(uri), "Digest", new NetworkCredential("administrator", "admin"));
 httpRequest.Credentials = cache;
 httpRequest.PreAuthenticate = true;
 using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
 {
    //DO CODE

 }

Before implementing an httpRequest in code, you should check it in a browser first. Enter your link in a browser and see if it brings up what you want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Seth Kitchen