我对我的C#
并不是太棒了,但我希望有人可以帮助我使用我的代码片段。第一个在C#
full .net框架中运行正常,第二个是我尝试将第一个更改为dotnet
核心(标准1.3),但它只是不起作用并且似乎禁止“使用”(流stream = response.GetResponseStream())“with”“errorMessage”:“远程服务器返回了error: (400)
Bad Request。”,但不明白为什么。我认为它与*异步调用有关,但实际上并不确定。
非常感谢,非常感谢帮助。
public static string AcquireTokenBySpn(string tenantId, string clientId, string clientSecret)
{
var payload = String.Format(SpnPayload, WebUtility.UrlEncode(ArmResource), WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
byte[] data = Encoding.ASCII.GetBytes(payload);
var address = String.Format(TokenEndpoint, tenantId);
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
JObject jObject = JObject.Parse(responseContent);
return (string)jObject["access_token"];
}
这是“核心片段”。
public static async Task<string> AcquireTokenBySpn(string tenantId, string clientId, string clientSecret, double apiVersion)
{
var payload = String.Format(SpnPayload, WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
var data = Encoding.ASCII.GetBytes(payload);
var address = String.Format(TokenEndpoint, tenantId, apiVersion);
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//request. ContentLength = data.Length;
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
JObject jObject = JObject.Parse(responseContent);
return (string)jObject["access_token"];
}
}
该错误肯定与GetResponseAsync()
有关。你需要检查一下那里发生了什么。 BTW。使用.NETCore 2.0而不是1.3更好,因为它支持.NET标准2.0库,因为它具有更强大的库支持。