Search code examples
c#asp.netiishttpwebrequest

WebRequest.GetResponse() is throwing error 401: Unauthorized


I have an ASP.NET application where I'm trying to output the previously-visited local aspx page to html (its a report and I want to store a static html copy of it as an archive). I store the uri of the local page with:

Session["SummaryURI"] = Request.Url.AbsoluteUri;

and then in the next page I retrieve it with:

string url = Session["SummaryURI"].ToString();

url = url.Replace("static=false", "static=true");
//MessageLabel.Text = url;

//CREATE THE NEW FILE
WebRequest req = WebRequest.Create(url);
WebResponse res = req.GetResponse();

The part req.GetResponse() is where I'm getting my error (401 Unauthorized).

Do I need to configure something in IIS to allow this?

Do I need to edit file permissions or something?

Thanks for your help

By the way this works fine on my local IIS but not on my test server.


Solution

  • 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.";
    }