Exception in Microsoft.Graph v5.42.0 when uploading file via GraphServiceClient...PutAsync()
Describe the bug A clear and concise description of what the bug is.
Started getting the following exception in Microsoft.Graph v5.42.0 when attempting to upload small files:
InnerException: Microsoft.Graph.Models.ODataErrors.ODataError: Cannot upload content to an item representing a folder.
at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.ThrowIfFailedResponse(HttpResponseMessage response, Dictionary2 errorMapping, Activity activityForAttributes, CancellationToken cancellationToken) at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory1 factory, Dictionary2 errorMapping, CancellationToken cancellationToken) at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory1 factory, Dictionary2 errorMapping, CancellationToken cancellationToken) at Microsoft.Graph.Drives.Item.Items.Item.Content.ContentRequestBuilder.PutAsync(Stream body, Action1 requestConfiguration, CancellationToken cancellationToken)
Exception: System.AggregateException: One or more errors occurred. (Cannot upload content to an item representing a folder.)
---> Microsoft.Graph.Models.ODataErrors.ODataError: Cannot upload content to an item representing a folder.
at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.ThrowIfFailedResponse(HttpResponseMessage response, Dictionary2 errorMapping, Activity activityForAttributes, CancellationToken cancellationToken) at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory1 factory, Dictionary2 errorMapping, CancellationToken cancellationToken) at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory1 factory, Dictionary2 errorMapping, CancellationToken cancellationToken) at Microsoft.Graph.Drives.Item.Items.Item.Content.ContentRequestBuilder.PutAsync(Stream body, Action1 requestConfiguration, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at fileTransfer_Services.SharePointService.UploadSmallFile(String filename, String localFilePath, String sharePointFilePath, Int32 retryCount) in C:\Reports\fileTransfer\App\services\remote\SharePointService.cs:line 631
To Reproduce Steps to reproduce the behavior:
This code works fine in Microsoft.Graph v5.41.0 and earlier:
// localFilePath example: "C:/Reports/fileTransfer/App/test_upload/jv_ rename.txt"
// sharePointFilePath example: "/POS team/JV Test/Test/jv_ rename.txt"
try
{
_logService.LogActivity($"SharePointService.UploadSmallFile() - Preparing to upload '{filename}' to sharePointFilePath: {sharePointFilePath}");
using FileStream fileStream = new(localFilePath, FileMode.Open);
DriveItem driveItem = _graphServiceClient.Drives[_driveId]
.Items["root"]
.ItemWithPath(sharePointFilePath)
.Content
.PutAsync(fileStream)
.Result;
if (driveItem.Name == filename)
{
uploadOk = true;
}
_logService.LogActivity($"SharePointService.UploadSmallFile() - File uploaded to driveItem.WebUrl: {driveItem.WebUrl}");
}
catch(Exception ex)
{
...
Expected behavior A clear and concise description of what you expected to happen.
In v5.41.0 and earlier, these are typical log entries:
SharePointService.UploadFileToSharePointFolder() - Attempting to upload file to SharePoint server: jv_filter_csv_1.csv . SharePointService.UploadFileToSharePointFolder() - Obtained file size, preparing to upload '77'-byte file: C:/Reports/fileTransfer/App/test_upload/jv_filter_csv_1.csv . SharePointService.UploadSmallFile() - Preparing to upload 'jv_filter_csv_1.csv' to sharePointFilePath: /POS team/JV Test/Test/jv_filter_csv_1.csv . SharePointService.UploadSmallFile() - File uploaded to driveItem.WebUrl: https://84lumber.sharepoint.com/sites/ITApplicationDevelopment/StoreApps/_layouts/15/Doc.aspx?sourcedoc=%7BEC19C27E-EF14-4CB5-8A7D-06CC9856D68D%7D&file=jv_filter_csv_1.csv&action=default&mobileredirect=true .
In v5.42.0, I get the exception listed earlier (and the file is not uploaded).
Desktop (please complete the following information):
- OS: Windows 11
- .NET 8.0.101
- Microsoft.Graph 5.42.0
Additional Comments
Note that uploading large files still works fine in v5.42.0 - so it's not entirely clear if the "small files" approach breaking indicates a bug or possibly a deprecation (in which case, I suppose I'll need to use the "large files" approach for all file uploads to SharePoint).
FWIW, here's the "large files" approach that I'm using, which works fine:
try
{
_logService.LogActivity($"SharePointService.UploadLargeFile() - Preparing to upload '{filename}' to sharePointFilePath: {sharePointFilePath}");
using Stream fileStream = new FileStream(localFilePath, FileMode.Open);
UploadSession uploadSession = _graphServiceClient.Drives[_driveId]
.Items["root"]
.ItemWithPath(sharePointFilePath)
.CreateUploadSession
.PostAsync(_uploadSessionRequestBody)
.Result;
LargeFileUploadTask<DriveItem> largeUploadTask = new(uploadSession, fileStream, _maxSliceSizeLarge);
if (_showLargeFileUploadProgress)
{
totalLength = fileStream.Length;
// create progress implementation (callback invoked after each slice uploaded)
IProgress<long> uploadProgress = new Progress<long>(uploadBytes =>
{
_logService.LogActivity($"SharePointService.UploadLargeFile() - Uploaded {uploadBytes} bytes of {totalLength} bytes");
});
// upload file
driveItemUploadResult = largeUploadTask.UploadAsync(uploadProgress).Result;
}
else
{
// upload file
driveItemUploadResult = largeUploadTask.UploadAsync().Result;
}
_logService.LogActivity($"SharePointService.UploadLargeFile() - driveItemUploadResult.UploadSucceeded: {driveItemUploadResult.UploadSucceeded}");
if (driveItemUploadResult.UploadSucceeded)
{
uploadOk = true;
}
}
catch(Exception ex)
...
The same for me with v5.42.0, and after downgrade to v5.41.0 upload works as expected.
Same error here I got this error message in v5.42.0 "Entity only allows writes with a JSON Content-Type header." same code in v5.41.0 works as expected.
Came here to report a VERY similar error with an Android project after upgrading to 5.42.0 (5.43.0 also has this issue). Previous working version I had was 5.39.0 but I can also confirm that 5.41.0 works.
Like the original bug report, I am also experiencing this while uploading a small file (MemoryStream), but to OneDrive. The code in question has been in effect and working for a long while.
The server appears to be sending back a 405 "Method Not Allowed" error. I did try explicitly setting the method, but that resulted with a 400 "Bad Request" error.
Here's the line that causes the issue with 5.42.0 and above:
await apiClient.RequestAdapter.SendAsync<DriveItem>(requestInformation, DriveItem.CreateFromDiscriminatorValue);
The same for me with v5.42.0 and V.43.0, after downgrade to v5.41.0 upload works as expected.
I have the same issue. error I get is same as @jregnard mentioned. I am running on Android and test in both .NET 6 as well as .NET 8 and get the same issue in both using v5.42.0 and v5.43.0. Like everyone else v5.41.0 works as expected.
Same error here I got this error message in v5.42.0 "Entity only allows writes with a JSON Content-Type header." same code in v5.41.0 works as expected.
Same error here I got this error message in v5.42.0 "Entity only allows writes with a JSON Content-Type header." same code in v5.41.0 works as expected.
+1. Also doesn't work in v5.43.0 and v5.44.0, still broken. Had to revert to v5.41.0.
I am also encountering this issue in 5.43.0. This has been open for 3 weeks, is anyone from the development team going to address this?
Had same issue. I had upgraded from 4.5.x to 5.44. Small tweaks to make the code compile.
Was receiving "One or more errors occurred. (Entity only allows writes with a JSON Content-Type header.)" from GraphApi.
Downgraded to 5.41 and PutAsync() for upload now works.
yikes, how is this still not addressed? can't upload files with this bug. downgrade to 5.4.1 fixed it for me. looks like the request URI is not being created correctly, doesn't contain the path to the file being uploaded
The issue here looks to be change in the generator that causes the PutAsync method to use a different URL template than the one the ItemWithPath passes to the constructor, therefore creating an incorrect URL.
PUT https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/148f1ef380baedb27f7adb3c93b45f194f5c3e16/src/Microsoft.Graph/Generated/Drives/Item/Items/Item/Content/ContentRequestBuilder.cs#L104
GET https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/148f1ef380baedb27f7adb3c93b45f194f5c3e16/src/Microsoft.Graph/Generated/Drives/Item/Items/Item/Content/ContentRequestBuilder.cs#L85
For now the guidance is to use 5.41.0 when using the PutAsync method as this is resolved from the generator.
Same here, reverting to 5.41.0 solves the issue.
Same problem here, reverted to 5.41.0
Is there any update on the resolution of this issue? It's still persisting even after updating to version 5.45.
It work for me 5.41.0 (but still not on 5.46)
Same problem here, reverted to 5.41.0
It's surprising that the reported bug hasn't been addressed even after two months.
Same issue here. Had to revert to 5.41.0.
I have a similiar issue. Beginning with version 5.42 the following statement fails:
await ServiceClient.Drives[rootDriveId].Items["root"].ItemWithPath(path).DeleteAsync(null, cancellationToken);
with the error: "Microsoft.Graph.Models.ODataErrors.ODataError: Root deletion is not allowed."
Reverting back to 5.41 fixes the issue. I am also using ItemWithPath() to identify the item.
Trying with the just-released version 5.47. The issue is still not fixed. Reverting to 5.41 is the only solution. It seems that they never take a look at the reported errors.
Tested with the just released 5.48 version. It seems to work properly this time. Thanks @andrueastman for fixing the issue.