ServerProtocolViolation with Http Basic on

I had a strange problem with my mobile application when we turned on Basic authentication on the http server. W32 version seems to work OK, but the same code ran Windows Mobile 5 with .NET CF throws: WebException with Status=ServerProtocolViolation.

Normally when a http server needs authorization, it responds with 401 Unauthorized then the client re-sends a request with proper Authorization header. In my case, .NET CF did not understood servers response, claiming that: The server response was not a valid HTTP response.

Request:

POST /X HTTP/1.1
Content-Type: text/xml
User-Agent: X
Content-Length: 384
Connection: Keep-Alive
Expect: 100-continue
Host: 217.X.X.X:Y

[...]

Response:

HTTP/1.1 401 Unauthorized
Server: X
WWW-Authenticate: Basic realm=X

Method POST requires a valid user name and password

Here client throws a WebException with Status=ServerProtocolViolation.

My solution was to present Authorization on the first request, since I know it will be needed. Since it solved the problem, I did not investigate strange Expect: 100-continue header, maybe it was the problem source. Oh and another thing, when server is more forthcoming and returns Connection: close and Content-Length: X headers the CF versions also works fine.

Anyway if you would need to create Authorization header yourself:

public static void SetBasicAuthorization(WebRequest request, string user,string password) {
string authorization = user + ":" + password;
byte[] bytes = Encoding.Default.GetBytes(authorization);
authorization = Convert.ToBase64String(bytes);
request.Headers.Add("Authorization", "Basic " + authorization);
}
Back to Top
%d bloggers like this: