I'm trying to read excel from sharepoint by using asp.net but its giving me following error fail: PowerBi_Report.Controllers.HomeController[0] An error occurred while processing the request: The remote server returned an error: (401) Unauthorized.

Rathor, Pradnya 0 Reputation points
2024-04-25T10:50:08.6333333+00:00

I have all the permissions for excel present in sharepoint still I'm getting same error can someone please help me out on this I'm pasting my code below

using System;

using System.Diagnostics;

using System.Net;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Logging;

using Microsoft.SharePoint.Client;

using PowerBi_Report.Models;

namespace PowerBi_Report.Controllers

{

public class HomeController : Controller

{

    private ListContent _ListContent = new ListContent();

    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)

    {

        _logger = logger;

    }

    public async Task<IActionResult> Index()

    {

        try

        {

            // Retrieve SharePoint credentials from environment variables

            string username = Environment.GetEnvironmentVariable("SHAREPOINT_USERNAME");

            string password = Environment.GetEnvironmentVariable("SHAREPOINT_PASSWORD");

            string dasId = Environment.GetEnvironmentVariable("DAS_ID");

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(dasId))

            {

                // Handle missing credentials

                throw new ApplicationException("SharePoint credentials not provided.");

            }

            // Concatenate username and DAS ID

            string fullUsername = $"{username}\\{dasId}";

            _logger.LogInformation($"Attempting to access SharePoint with username: {fullUsername}");

            // SharePoint URL

            string sharePointUrl = "https://atos365.sharepoint.com/:x:/r/sites/100005071/";

            // File path in SharePoint

            string filePath = "Shared Documents/IRIS/IRIS Mapping _All Contracts.xlsx";

            // Create a client context object with the site URL

            using (var ctx = new ClientContext(sharePointUrl))

            {

                // SharePoint credentials

                ctx.Credentials = new NetworkCredential(fullUsername, password);

                // Get the library

                var library = ctx.Web.Lists.GetByTitle("100005071");

                // Get the file

                var file = library.RootFolder.Files.GetByUrl(filePath);

                ctx.Load(file);

                ctx.ExecuteQuery();

                // Download the file

                using (var fileStream = System.IO.File.Create("IRIS Mapping _All Contracts.xlsx"))

                {

                    var fileContent = file.OpenBinaryStream();

                    ctx.ExecuteQuery();

                    fileContent.Value.CopyTo(fileStream);

                }

            }

        }

        catch (Exception ex)

        {

            // Log and handle any exceptions that occur during the process

            _logger.LogError($"An error occurred while processing the request: {ex.Message}");

            return View("Error", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

        }

        // Return the view with the populated _ListContent object

        return View();

    }

    public IActionResult Privacy()

    {

        return View();

    }

}
```}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,596 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,502 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,996 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.