使用RestSharp获取MS Graph令牌



我是使用MS Graph和新版RestSharp的新手。我在VB.NET中组装了一个简单的控制台应用程序来学习这个过程。我花了太多时间在互联网上寻找解决方案,但没有得到我想要的答案。最终目标是自动将文件上传到OneDrive帐户。因此,我在Azure上为此应用程序创建了一个应用程序注册。然后为了测试,我创建了一个控制台应用程序来测试这个过程是如何工作的。我使用的是RestSharp的最新版本,它与我使用的版本非常不同。控制台应用程序调用下面显示的一个简单子例程,以获取调用Graph的令牌。当我运行时,我得到错误:";System.dll中的System.Net.ProtocolViolationException";以及";mscorlib.dll中的System.Net.ProtocolViolationException";。代码如下:

Dim client As New RestClient("https://login.microsoftonline.com/f8cde-----/oauth2/v2.0/token")
Dim request As New RestRequest(Method.Post)
request.AddHeader("Content-Type", "application/x-www-form-urlencoded")
request.AddHeader("Host", "login.microsoftonline.com")
Dim body As String = "client_id=8e4---------" &
"scope=api://8e4da056-8425-4-.default" &
"client_secret=Piy7Q~7----------" &
"grant_type=client_credentials"
request.AddBody(body)
Dim response As RestSharp.RestResponse = Await client.ExecuteAsync(request)
Console.Write(response.Content.ToString)
Console.ReadKey()
End Sub

我承认我真的不知道自己在这里做什么,但我想学习。

我可以建议花点时间阅读文档。如果使用RestRequestAPI构建请求,则RestSharp会正确地形成请求。

以下是您需要做的:

Dim options = New RestClientOptions("https://login.microsoftonline.com/f8cde-----/oauth2/v2.0/token")
options.BaseHost = "login.microsoftonline.com"
Dim client = New RestClient(options)
Dim request As New RestRequest(Method.Post)
request.AddParameter("client_id", "8e4---------")
request.AddParameter("client_secret", "Piy7Q~7----------")
request.AddParameter("grant_type", "client_credentials")
Dim response = Await client.ExecuteAsync(request)

最新更新