WebRequest.GetResponse() is throwing error 401: Unauthorized
Maybe a proxy bothers you. Look here to see how to disable it: How to remove proxy from WebRequest and leave DefaultWebProxy untouched
Also, maybe you have missing slash at the of your endpoint:
Endpoint = $"https://your.api.com/id=111/"; /* <-- attention to the trailing slash */
As of right now I don't have access to the IIS settings so I couldn't enable Anonymous Authentication
which is very possible why Cybernate's answer was not working for me. I did find however a simpler method that worked. Instead of using a WebRequest
I found that I could do the same thing with Server.Execute
. Below is my new solution:
string strHTML = String.Empty;
using (var sw = new StringWriter())
{
Server.Execute([path-to-local-aspx], sw);
strHTML = sw.ToString();
}
string relativeReportPath = [relative-path-to-new-html-file];
using (StreamWriter writer = File.CreateText(Server.MapPath(relativeReportPath)))
{
writer.WriteLine(strHTML);
MessageLabel.Text = "Your report is ready. Click Close to close the window.";
}
If you cannot enable Anonymous Authentication, try adding this to your WebRequest:
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
I think the issue is because authentication on the test IIS server. Two options:
1) Enable "Anonymous Authentication" for the Site on test IIS Server.
2) (Recommended) Before making the request to test server use the code template below with right username/password/domain information that can be authenticated against the test server.
System.Net.NetworkCredential netCredential =
new System.Net.NetworkCredential("<USER_NAME>", "<PASSWORD>", "<DOMAIN>");
req.Credentials = netCredential;