Search code examples
c#cookies.net-corehttpwebrequesthttpwebresponse

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


Solution

  • 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.