Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

httpwebrequest - C# Network credentials not being passed to server?

Edit: Using:

byte[] authBytes = System.Text.Encoding.UTF8.GetBytes(user + ":" + password);
wr.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);

Seems to work fine.

I have an application that communicates with a CMS. I'm currently trying to get this client to be able to upload text/xml data to the CMS using a "POST" method.

I can pass this through using curl perfectly fine:

curl -u user:password -H "Content-Type:text/xml" -d "<element>myXML</element>" serverURL

However, trying to use the HttpWebRequest in C# I can't get the server to return what I want it to. So I fired up Wireshark and had a look at what was actually being passed through, and it's pretty much identical except for the fact that when using curl I can see:

Authorization: Basic <a bunch of hex>=

Credentials: user:password

In the HTTP header fields, while in the output from my client, these header fields are simply not present. ("Credentials:" isn't actually there in plain text, it's a subtree of "Authorization:" - so I'm not sure where it's getting it from, but the username and password are correct.)

The C# code I'm trying to use to set the credentials for the webrequest is something like this:

NetworkCredential myCred = new NetworkCredential(
                    user, password, serverURL);

CredentialCache myCache = new CredentialCache();

myCache.Add(new Uri(serverURL), "Basic", myCred);

HttpWebRequest wr = (HttpWebRequest) HttpWebRequest.Create(serverURL);
wr.Credentials = myCache;

I've tried just setting the credentials like this too (and without specifying serverURL):

wr.Credentials = new NetworkCredential(user,password,serverURL);

But that still doesn't make it show up in wireshark. Does anyone have any idea if:

A) That authorization information should actually be in the HTTP header for this to work, and

B) If it is - then how do I make C# put it in? I only seem to be able to find decent examples using the default credentials, which doesn't apply to what I'm doing.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.NET's WebRequest has an infuriating default behavior where it only sends credentials after receiving an HTTP 401 Not Authorized response.

Manually adding the credentials header (as you've done) seems to be the best solution available.

More details in this post


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...