step-up-labs / firebase-storage-dotnet

C# library for Firebase Storage
MIT License
140 stars 35 forks source link

GetDownloadUrlAsync fails with 400 #40

Closed fabri777 closed 2 years ago

fabri777 commented 3 years ago

Depending on your configuration HttpClient.GetAsync(url) in PerformFetch may unescape or not the escaped path by GetEscapedPath, leading to a 400 response from Firebase.

The following will fix the issue:

 private async Task<T> PerformFetch<T>()
        {
            var url = this.GetDownloadUrl();
            var resultContent = "N/A";

            try
            {
                var uri = new Uri(url);
                ForceCanonicalPathAndQuery(uri);

                using (var http = await this.storage.Options.CreateHttpClientAsync().ConfigureAwait(false))
                {
                    var result = await http.GetAsync(uri);
                    resultContent = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var data = JsonConvert.DeserializeObject<T>(resultContent);

                    result.EnsureSuccessStatusCode();

                    return data;
                }

            }
            catch (Exception ex)
            {
                throw new FirebaseStorageException(url, resultContent, ex);
            }
        }

        void ForceCanonicalPathAndQuery(Uri uri)
        {
            string paq = uri.PathAndQuery; // need to access PathAndQuery
            FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
            ulong flags = (ulong)flagsFieldInfo.GetValue(uri);
            flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
            flagsFieldInfo.SetValue(uri, flags);
        }
stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 2 years ago

Closing the issue due to inactivity. Feel free to re-open