.netasp.net-coreziphttpclient

Why HttpClient.GetAsync returns 302 while trying to download zip file from external server? (FIXED)


in my project i have file dowloader spot. Any file i can dowload except zip. When i try to dowload zip file from other server it returns to me redirect. Do you have any idea what can be cause of that?

I thought it was about content of file. I tried to download dummy zip but also it returns redirect.

  if (!File.Exists(filePath))
  {
      try
      {

          var response = await client.GetAsync(prevUIServer + filename);

          if (response.IsSuccessStatusCode)
          {
              using (var fileStream = File.Create(filePath))
              {
                  await response.Content.CopyToAsync(fileStream);
                  fileStream.Close();
              }
          }
          else
          {
              throw new Exception($"Error downloading file: {prevUIServer}{filename}, Status Code: {response.StatusCode}");
          }
      }
      catch (Exception ex)
      {
          throw new Exception($"Error downloading file: {prevUIServer}{filename}  + filePath {filePath}  + filename = {_fn}, {ex.Message}");
      }
  }

REASON

We found the reason. One of the server which try to download zip file has security policy doesnt allow to download zip file from outsource. That's why we got redirect when we try to download from external server.


Solution

  • In my project i have file downloader spot. Any file i can dowload except zip. When i try to dowload zip file from other server it returns to me redirect. Do you have any idea what can be cause of that?

    It would be great if you could share your relevant code snippet in order to inspect your issue in details.

    However, when HttpClient.GetAsync returns a 302 status code (Found), it means that the server is redirecting the request to another URL. This redirection can happen due to various reasons set by the server's configuration or logic.

    First of all, the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the target URI for future requests.

    Another reason, might be server may have rules configured to redirect certain requests to a different URL. This could be based on the requested URL, headers, cookies, or other factors.

    I have tried to simulate your scenario to download zip file from a test server and I got the expected output and zip file has been downloaded successfully.

    Let's have a look how I did that.

    In order to execute the test, I need a file path where I would download the zip file. I would assign a file name and then I will call the server where the zip is currently residing.

    Finally, I will call that endpoint and read the byte data using ReadAsByteArrayAsync and write into that filepath location.

    Controller Action:

    public async Task<IActionResult> Index()
    {
        string url = "https://www.dwsamplefiles.com/?dl_id=559";
        string filename = "file.zip";
    
        try
        {
            string downloadsPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads\\";
            string filePath = Path.Combine(downloadsPath, filename);
            await DownloadFileAsync(url, filePath);
            Console.WriteLine($"File downloaded successfully to {filePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error downloading file: {ex.Message}");
        }
        return Ok();
    }
    

    Note: This is my demo url where my zip file is uploaded.

    Method for calling endpoint:

    private async Task DownloadFileAsync(string url, string filePath)
    {
        using var handler = new HttpClientHandler
        {
            AllowAutoRedirect = true // Note This is the default behavior
        };
    
        using var httpClient = new HttpClient(handler);
        var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
    
        if (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
        {
            //I am handling redirect manually
            var redirectUrl = response.Headers.Location.ToString();
            response = await httpClient.GetAsync(redirectUrl);
    
            if (response.IsSuccessStatusCode)
            {
                await SaveFileAsync(response, filePath);
            }
            else
            {
                throw new Exception($"Failed to download file from redirect URL: {response.StatusCode}");
            }
        }
        else if (response.IsSuccessStatusCode)
        {
            // No redirect, download the file directly
            await SaveFileAsync(response, filePath);
        }
        else
        {
            throw new Exception($"Failed to download file: {response.StatusCode}");
        }
    }
    

    Note: Keep in mind you can handle the redirection manually as well, which I did above.

    File writing in location:

    private async Task SaveFileAsync(HttpResponseMessage response, string filePath)
    {
        var content = await response.Content.ReadAsByteArrayAsync();
        await System.IO.File.WriteAllBytesAsync(filePath, content);
    }
    

    Output:

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    Note: Please refer to this official document for redirection details