首页 > 解决方案 > login.microsoftonline 和 restsharp

问题描述

我尝试了几件事,这个在邮递员中工作 在此处输入图像描述

但在 C# 中它不起作用;它给了我一个空白页 在此处输入图像描述

关于如何解决它的任何想法?

标签: c#asp.net-corepostman

解决方案


这是 System.Net.HttpClient 的示例。我使用 JSON.NET 来提取令牌,但您可以以任何方式解析结果:

//create a shared client somewhere convenient
HttpClient client = new HttpClient();

...

string tokenurl = "https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxxxxx/oauth2/v2.0/token";
string appregClientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string appregClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

HttpRequestMessage tknMsg = new HttpRequestMessage(HttpMethod.Post, tokenurl);
Dictionary<string, string> tknBody = new Dictionary<string, string>{
    { "client_id", appregClientId },
    { "scope", "https://graph.microsoft.com/.default" },
    { "client_secret", appregClientSecret },
    { "grant_type", "client_credentials" }
};

var content = new FormUrlEncodedContent(tknBody);
tknMsg.Content = content;
var tknResponse = await client.SendAsync(tknMsg);

string tknResponseJson = await tknResponse.Content.ReadAsStringAsync();
JObject jobj = JObject.Parse(tknResponseJson);

string accessTkn = (string)jobj["access_token"];

推荐阅读