尝试通过Code访问cherwell REST api时,我收到500内部服务器错误,试图返回令牌以进行其他调用。我已经验证所有信息(用户名,密码,ClientID和客户端密码)都是正确的。我还验证了服务器已启动并接受请求。我的代码肯定有问题。任何帮助都会很棒!
string token = "";
string responseBody;
string serverName = "ql1cwbeta1";
//initialize web client
using (WebClient webClient = new WebClient())
{
// pull down parameters for body
string grantType = ConfigurationManager.AppSettings["grant_type"];
string clientId = ConfigurationManager.AppSettings["client_id"];
string username = ConfigurationManager.AppSettings["username"];
string password = ConfigurationManager.AppSettings["password"];
string authMode = ConfigurationManager.AppSettings["auth_mode"];
//add parameters in headers
webClient.Headers.Add("Accept", "application/json");
// adding parameters in body
NameValueCollection values = new NameValueCollection
{
{"grant_type", grantType},
{"client_id", clientId},
{"username", username},
{"password", password},
{"auth_mode", authMode}
};
try
{
byte[] responseBytes = webClient.
UploadValues("http://" + serverName + "/CherwellAPI/token?auth_mode=" + authMode + "&api_key=" + clientId, "POST", values);
responseBody = Encoding.UTF8.GetString(responseBytes);
}
catch (Exception exception)
{
return exception;
}
答案 0 :(得分:0)
希望以下代码可以为您提供帮助。
public static string TokenRequest()
{
try
{
// Create HTTP Web Request for the token request
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(Values.TokenURL);
byte[] data = Encoding.ASCII.GetBytes("username=" + Username + "&password=" + Password + "&client_id=" + ClientId + "&grant_type=" + GrantType);
// Set request verb POST, content type and content length (length of data)
tokenRequest.Method = "POST";
tokenRequest.ContentType = "application/x-www-form-urlencoded";
tokenRequest.ContentLength = data.Length;
// Stream request data
using (Stream stream = tokenRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
// Get the response and read stream to string
using (WebResponse response = tokenRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
// responseText = sr.ReadToEnd();
return sr.ReadToEnd();
}
}
}
}
catch (WebException ex)
{
// Catch error for bad URL (404) or bad request (400) resulting from bad input (username, password, client id, grant type in token request)
if (ex.Message.Contains("400"))
{
// do something for bad request
}
else if (ex.Message.Contains("404"))
{
// do something for not found
}
else
{
// unknown error, do something
}
return null;
}
catch (Exception ex)
{
// General Exception
return null;
}
}
答案 1 :(得分:0)
供将来参考 - 您可以将客户端 ID 作为查询字符串的一部分如果所有参数都包含在查询字符串中,但是如果您还发送有效负载,那么 authmode 应该是唯一的在查询字符串中。
它将接受所有这些参数作为查询字符串。
但是,您应该知道,对于 Cherwell,如果您使用的是 LDAP 身份验证/用户帐户,则可能需要对您的用户名值进行 URL 编码。
某些特殊字符会破坏 auth 命令。具体来说,如果不使用 %5C 转义,则为域包含反斜杠可能会导致问题,我认为这会导致 400 错误。
如果您在管理控制台的“安全设置”页面中选择了未为浏览器应用启用的身份验证模式,也可能导致错误;)