【发布时间】:2019-12-13 17:43:33
【问题描述】:
当我尝试使用 Microsoft Graph API 使用守护程序应用将文件上传到 OneDrive 时,我收到错误 400 Bad Request。我使用 HttpClient,而不是 GraphServiceClient,因为后者假定交互并与 DelegatedAuthenticationProvider(?) 一起使用。
- 该应用程序已在 AAD 中注册并具有正确的应用程序权限(Microsoft Graph / File ReadWrite.All)
- 注册是针对一个租户,没有重定向网址(根据说明)
主要方法 Upload 通过 Helper AuthenticationConfig 获取 AccessToken,并使用 Helper ProtectedApiCallHelper 将文件放入 OneDrive/SharePoint。
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
var toegang = new AuthenticationConfig();
var token = toegang.GetAccessTokenAsync().GetAwaiter().GetResult();
var httpClient = new HttpClient();
string bestandsnaam = file.FileName;
var serviceEndPoint = "https://graph.microsoft.com/v1.0/drive/items/{Id_Of_Specific_Folder}/";
var wurl = serviceEndPoint + bestandsnaam + "/content";
// The variable wurl looks as follows: "https://graph.microsoft.com/v1.0/drive/items/{Id_Of_Specific_Folder}/proefdocument.txt/content"
var apicaller = new ProtectedApiCallHelper(httpClient);
apicaller.PostWebApi(wurl, token.AccessToken, file).GetAwaiter();
return View();
}
我使用以下标准助手 AuthenticationConfig.GetAccessToken() 获得了正确的访问令牌
public async Task<AuthenticationResult> GetAccessTokenAsync()
{
AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
return result;
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
...
return result;
}
}
使用 AccessToken、Graph-Url 和要上传的文件(作为 IFormFile)调用 Helper ProtectedApiCallHelper.PostWebApi
public async Task PostWebApi(string webApiUrl, string accessToken, IFormFile fileToUpload)
{
Stream stream = fileToUpload.OpenReadStream();
var x = stream.Length;
HttpContent content = new StreamContent(stream);
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequestHeaders = HttpClient.DefaultRequestHeaders;
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
// Here the 400 Bad Request happens
HttpResponseMessage response = await HttpClient.PutAsync(webApiUrl, content);
if (response.IsSuccessStatusCode)
{
return;
}
else
{
//error handling
return;
}
}
}
编辑
请参阅下面的工作解决方案。
【问题讨论】:
标签: c# asp.net-core sharepoint microsoft-graph-api onedrive