Search code examples
azureazure-functionsmicrosoft-graph-apihttp-status-code-302http-status-code-502

Deal with HttpStatus 302 in Azure Function


In Azure Function I'm trying to return a pdf file from the MS Graph Converter (Doc)

the file is return on an 302 Http Status, not a big deal in local, all work fine, but when i publish on azure function i've got this error :

502 - Web server received an invalid response while acting as a gateway or proxy server. There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

My code :

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
             .Create("")
             .WithTenantId("")
             .WithClientSecret("") 
             .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);


            var graphClient = new GraphServiceClient(authProvider);


  var token = await authProvider.ClientApplication.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();


            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);
            try
            {
                var response = await httpClient.GetAsync($"https://graph.microsoft.com/v1.0/drives/{Drive_Id}/items/{Item_Id}/content?format=pdf");

                log.LogInformation($"Status Code : {response.StatusCode}");

                if (response.StatusCode == System.Net.HttpStatusCode.Redirect)
                {
                    var bytes = await httpClient.GetByteArrayAsync(response.Headers.Location);

                    return new FileContentResult(bytes, "application/pdf");
                }

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var bytes = await response.Content.ReadAsByteArrayAsync();

                    return new FileContentResult(bytes, "application/pdf");
                }

            }
            catch (Exception ex)
            {
                log.LogInformation($"Error : {ex.Message}");
            }

            return new NotFoundResult();

I think there is some kind of configuration to allow 302 temporary redirect or something like that..

Any help should be appreciate


Solution

  • I found that my pb was on the upload of the file, the stream was close too early and that was making the function to exit...