KoenZomers / OneDriveAPI

API in .NET Framework 4.8.0, .NET Core 3.1 and .NET 6.0 to communicate with OneDrive Personal and OneDrive for Business
Eclipse Public License 1.0
109 stars 34 forks source link

[BUG] Error when Creating Link to Share Item #42

Closed miroppb closed 9 months ago

miroppb commented 11 months ago

Describe the bug I'm trying to create a link to an uploaded file

((OneDriveGraphApi)oneDriveClient).ShareItem(upload, KoenZomers.OneDrive.Api.Enums.OneDriveLinkType.View);

File gets uploaded without issue, but when I try to generate a link, I get the error

One or more parameters of the operation 'createLink' are missing from the request payload.

Versions (please complete the following information):

miroppb commented 9 months ago

Bump...

miroppb commented 9 months ago

Was able to resolve my issue by using a separate HttpClient call to https://graph.microsoft.com/v1.0/, with the Access Key that the OneDrive client gets when authenticating

public async Task<string> GetShareLinkAsync(string fileID, string type, string scope)
{
    object result = null;
    using (HttpClient client = new HttpClient())
    {
        var contentType = new MediaTypeWithQualityHeaderValue("application/json");
        var baseAddress = @"https://graph.microsoft.com/v1.0/";
        var api = $"drive/items/{fileID}/createLink";
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Add(contentType);
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {ODAccess}");

        var data = new Dictionary<string, string>
        {
            {"type", type},
            {"scope", scope}
        };

        var jsonData = JsonConvert.SerializeObject(data);
        var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");

        var response = await client.PostAsync(api, contentData);

        if (response.IsSuccessStatusCode)
        {
            var stringData = await response.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<object>(stringData);
        }
    }

    return JToken.FromObject(result).SelectToken("link.webUrl").Value<string>();
}

Used https://stackoverflow.com/questions/51688525/how-to-upload-files-to-one-drive-from-net and https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createlink?view=odsp-graph-online as a guide