.Net CF 2.0 HttpWebRequest pre-authentication and sending credentials on first request

纵饮孤独 提交于 2019-12-23 04:17:06

问题


I'm attempting to communicate with bit.ly's REST API using their modified version of basic authentication. However in order for this to work HttpWebRequest needs to attach the credentials on the first request, however, HttpWebRequest will not send credentials on the first request and will wait for a 401 before sending any credentials even if PreAuthenticate is set to true (with PreAuthenticate it will send credentials for all subsequent requests).

I have attempted the following to get HttpWebRequest to work the way bit.ly requires it:

(1) Send the request in the format http://username:password@api.bi.ly/method .

Not supported by bit.ly (as this is a fake implementation of basic authentication they only check the header).

(2) Manually inject the "Authorization" header into the HttpWebRequest.

Not possible in the .Net CF as the Authorization header is protected and any attempt to modify a protected header value fails and throws an ArgumentException.

(3) Inherit HttpWebRequest or WebRequest in another class as to implement the required behavior.

Not possible as The HttpWebRequest class is registered to service requests for HTTP and HTTPS schemes by default. Attempts to register a different WebRequest descendant for these schemes will fail as duplicate prefixes are not allowed.

So anyone got any suggestions?


回答1:


A note on (2). I used the method described at http://blog.kowalczyk.info/article/Forcing-basic-http-authentication-for-HttpWebReq.html to inject an authorization header and it works fine in .NET CF 2.0.

public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
    string authInfo = userName + ":" + userPassword;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    req.Headers["Authorization"] = "Basic " + authInfo;
}


来源:https://stackoverflow.com/questions/1058252/net-cf-2-0-httpwebrequest-pre-authentication-and-sending-credentials-on-first-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!