Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now! Learn more

Reply
Anonymous
Not applicable

401 - Unauthorized error during Dataset Refresh

I am trying to do the Dataset refresh for a PowerBI Report. I created the gateway and I am able to do the dataset refresh from the admin portal. I could validate that the refresh happend successfully from UI i.e. Last Refresh column in the Admin portal. But when I try to do the refresh from a C# webapi code, I am getting the below mentioned error.

 

Error Message:
The remote server returned an error: (401) Unauthorized.

Stack Trace:
at System.Net.HttpWebRequest.GetResponse()
at BlueSkyPowerBIService.Controllers.PowerBIController.<RefreshDatasetsForReports>d__13.MoveNext() in C:\Krishnan\RSI\SourceCode\Bluesky Developement\BlueSky Development\BlueSkyPowerBIService\BlueSkyPowerBIService\Controllers\PowerBIController.cs:line 258

Before the refresh code, I am able to do the authentication agains the Azure AD and it succeeds and generated the auth token, but when it call the API to refresh it crashes with the above said error.

Please find my code which i am use for data refresh

List<ReportDetails> reportDetailsList = new List<ReportDetails>();

            var result = new EmbedConfig();
            ReportDetails reportDetails = new ReportDetails();
            try
            {
                result = new EmbedConfig { Username = username, Roles = roles };
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    result.ErrorMessage = error;
                    //return View(result);
                    return null;
                }
                var credential = new UserPasswordCredential(Username, Password);

                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "Authentication Failed.";
                    //return View(result);
                    return null;
                }

                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                {
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsAsync();
                    for (int index = 0; index < reports.Value.Count; index++)
                    {
                        reportDetails = new ReportDetails();
                        Report report = reports.Value[index];

                        HttpWebRequest request;

                        if (report.Id == "6317f207-57d3-4f5f-9644-18bfbb9bef99")
                        {
                            var url = "https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/refreshes";
                            request = System.Net.HttpWebRequest.CreateHttp(String.Format(url, GroupId, report.DatasetId));

                            request.KeepAlive = true;
                            request.Method = "POST";
                            request.ContentLength = 0;

                            request.Headers.Add("Authorization", String.Format("Bearer {0}", authenticationResult.AccessToken));

                            using (Stream writer = request.GetRequestStream())
                            {
                                var response = (HttpWebResponse)request.GetResponse();
                                Console.WriteLine("Dataset refresh request{0}", response.StatusCode.ToString());
                            }
                        }
                    }//end for(int index=0; index< reports.Value.Count; index++)
                    return reportDetailsList;
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault());
            }
            catch (Exception exc)
            {
                result.ErrorMessage = exc.ToString();
            }

Any ideas why I am getting this error? How to fix this issue?

3 REPLIES 3
v-jiascu-msft
Microsoft Employee
Microsoft Employee

Hi @Anonymous,

 

 

Could you please mark the proper answers as solutions?

 

Best Regards,

Dale

Community Support Team _ Dale
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
Anonymous
Not applicable

Hi @Anonymous,

 

- Dataset.ReadWrite.All is the required permission that you're PowerBi Application should have in order to execute a refresh action.

(https://docs.microsoft.com/en-us/rest/api/power-bi/datasets/refreshdatasetingroup)

If this is the problem, you should go to Azure Active Directory find the powerbi application and add the above permissions. 

 

Hope it helps.

 

Thanos

v-jiascu-msft
Microsoft Employee
Microsoft Employee

Hi @Anonymous,

 

What's in the "PowerBIController.cs:line 258"? The error message indicates something wrong here. I would suggest you check if the user has the Edit permission of the dataset.

 

Best Regards,

Dale

 

Community Support Team _ Dale
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Helpful resources

Announcements
Power BI DataViz World Championships

Power BI Dataviz World Championships

The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now!

December 2025 Power BI Update Carousel

Power BI Monthly Update - December 2025

Check out the December 2025 Power BI Holiday Recap!

FabCon Atlanta 2026 carousel

FabCon Atlanta 2026

Join us at FabCon Atlanta, March 16-20, for the ultimate Fabric, Power BI, AI and SQL community-led event. Save $200 with code FABCOMM.