admin管理员组

文章数量:1332361

I am trying to have an ASP.NET MVC app to upload file to Sharepoint, however, I got 401 error. I added access to the app API permission, not sure what else I need. It failed at context.ExecuteQuery().

Please advise.

// http post method
[HttpPost]
public async Task<ActionResult> UploadLargeFile(IFormFile file)
{
    // Authenticate with SharePoint
    var context = await GetSharePointContext();
    var web = context.Web;
    context.Load(web);

    // Specify the target document library
    var targetLibrary = web.Lists.GetByTitle("Documents");
    context.Load(targetLibrary);
    context.ExecuteQuery();
}

// Authentication method using Microsoft Identity Platform
private async Task<ClientContext> GetSharePointContext()
{
    var app = ConfidentialClientApplicationBuilder
               .Create(ClientId)
               .WithTenantId(TenantId)
               .WithClientSecret(ClientSecret)
               .Build();

    var scopes = new[] { "/.default" };

    var authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();

    var context = new ClientContext(SharePointSiteUrl);
    context.ExecutingWebRequest += (s, e) =>
           {
               e.WebRequestExecutor.WebRequest.Headers["Authorization"] =
                   "Bearer " + authResult.AccessToken;
           };

    return context;
}

本文标签: cASPNET MVC upload file to sharepoint online get 401 unauthorized errorStack Overflow