在C#中开发的.net Web服务中出现“未经授权”错误

时间:2009-12-04 17:36:10

标签: c# .net asp.net

请求失败,HTTP状态为401:未经授权。为什么呢?

TravelCodesTranslator ws = GetEncodeDecodeWS();

// Create and set up the credentials for XmlSelectWebService
 string UserName = "username";
 string Password = "pwd";
// Xml Select uses Basic Authentication
NetworkCredential credentials = new NetworkCredential(UserName, Password);
CredentialCache cc = new CredentialCache();
ws.PreAuthenticate = true;
ws.Credentials = credentials;

XmlElement response;

if (_requestType == "Encode")
{
    response = ws.Encode(request.DocumentElement); // got error of
                                                   // "The request failed
                                                   //  with HTTP status 401:
                                                   //  Unauthorized."
}
else
{
    response = ws.Decode(request.DocumentElement);
}

1 个答案:

答案 0 :(得分:2)

更改

ws.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

ws.Credentials = credentials 

提示:错误消息非常清楚。它说你的凭据不正确。然后我会检查用户名和密码是否正确。如果它们是正确的,那么我会看看它们是否被正确分配给了请求。