我正在尝试调用在邮递员中工作正常的休息服务来生成 OAuth 令牌,但是当我在 WCF 4.0 代码中尝试时,我收到错误
远程服务器返回错误:(401) 未经授权。
在这行代码
using (var response = (HttpWebResponse)request.GetResponse())
有人可以指导我解决这个问题吗?
这是我的完整代码:
public static string GetAccessToken(string tokenUrl, string clientId, string clientSecret, string grantType)
{
try
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
var request = (HttpWebRequest)WebRequest.Create(tokenUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Prepare the data to post.
var postData = @"client_id=" + Uri.EscapeDataString(clientId) + "&" +
@"client_secret " + Uri.EscapeDataString(clientSecret) + "&" +
@"grant_type=" + Uri.EscapeDataString(grantType);
var byteArray = Encoding.UTF8.GetBytes(postData);
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
string responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
}
catch (Exception ex)
{
// Handle exceptions
Console.WriteLine("Error: " + ex.Message);
return null;
}
}
问题已修复,client_secret后面缺少=并且client_secret开头有空格