Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpWebRequest response error (401)

Please excuse me if I look as though I'm doing something stupid here. I've tried browsing other stack overflow questions for the answer to my issue, yet do not seem to be getting anywhere.

I'm working on a dotnet core MVC application and wanting to return some data from a remote server. I am using the HttpWebRequest class.

In Fiddler I executed the following using the composer.

enter image description here

As you can see its a simple GET request with two cookies passed in the header.

This works great and returns me exactly what I need.

I then compose my request in the dotnet world as follows:

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

 request.CookieContainer = new CookieContainer();

 request.CookieContainer.Add(new Cookie("name", "value", "/", "localhost"));

(did not include second cookie for purpose of question)

I then call:

var httpResponse = (HttpWebResponse)request.GetResponse();

Yet receive 'The remote server returned an error: (401) Unauthorized'

Any ideas what I'm doing wrong here? I tried to add the following line of code for testing purposes, but still no luck.

request.ServerCertificateValidationCallback = delegate { return true; };

All answers appreciated. Plus as I mentioned, I'm no expert so I could just be doing something daft!

James

like image 531
James Sherburn Avatar asked Jul 16 '26 12:07

James Sherburn


2 Answers

I think your request is defaulting to POST, but your Fiddler example is doing a GET.

Try adding:

            request.Method = "GET";
            request.ContentType = "text/xml; encoding='utf-8'";
like image 176
Scrappydog Avatar answered Jul 18 '26 01:07

Scrappydog


In the Cookie constructor, you are setting the cookie's domain as "localhost" which means it will only be delivered to requests to the localhost domain. It should be set to the domain you are actually sending the request to.

like image 35
Ed T Avatar answered Jul 18 '26 01:07

Ed T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!