0

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data. To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors

 {"Message":"Authorization has been denied for this request."}

Steping step by step in debuger I fund that following lines of code doing 401 error

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.Credentials = new NetworkCredential(username, password);
        wr.Method = "POST";
        wr.ContentType = "application/json";
        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
        wr.ContentLength = byteArray.Length;
        using (System.IO.Stream dataStream = wr.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
        }

Later in code when I do wr.GetResponse() I do get status 200OK.

My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?

David Storey
  • 29,166
  • 6
  • 50
  • 60
adopilot
  • 4,340
  • 12
  • 65
  • 92

1 Answers1

1

If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:

Composer tab -> Options tab -> Automatically Authenticate

Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:

HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");

HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;
Kiran
  • 56,921
  • 15
  • 176
  • 161
  • Thanx on answer I switched to using HttpClient But fiddler still cache HTTP 401 but now it happens in: var dnnUser = response.Content.ReadAsAsync().Result; – adopilot May 24 '13 at 08:54
  • I am unable to understand your statement "still cache HTTP 401"...are you seeing this error even after setting the Fiddler settings as above?...Could you share your repro project? – Kiran May 24 '13 at 17:30