简体   繁体   中英

Null response when using RestSharp to download a file

I am attempting to update the RestSharp file download portion code in one of my applications. Apparently the .SaveAs() is being depricated, so I'm trying to follow their updated example for working with files. However, my response is always null, and the temp file that is created doesn't seem to be filled with the data I'm attempting to save.

Here's what I have so far:

        var tempFile = Path.GetTempFileName();
        using var writer = File.OpenWrite(tempFile);

        var client = new RestClient("https://provider-api.spotify.com/v1/analytics");
        var request = new RestRequest("{licensor}/enhanced/tracks/{year}/{month}/{day}", Method.GET);
        request.AddHeader("Authorization", $@"Bearer {token}");
        request.AddUrlSegment("licensor", "licensor_name");
        request.AddUrlSegment("year", 2021);
        request.AddUrlSegment("month", 1);
        request.AddUrlSegment("day", 10);

        var checkResponse = client.Execute<SpotifyTracksResourceModel>(request);

        if (checkResponse.Content == "")
        {
            Console.WriteLine("No data");
        }

        request.ResponseWriter = responseStream =>
        {
            using (responseStream)
            {
                responseStream.CopyTo(writer);
            }
        };
        var response = client.DownloadData(request);

I threw in the checkResponse code to ensure that I am actually getting data back, and I am in fact getting data. But as I said, once it gets to the var response =... line, it comes back NULL, and nothing has been written to that temp file.

Thank you in advance for any help with this!

So it ended up being a combination of a few little things I needed to tweak. But the biggest things were updating the RestSharp NuGet package, and closing off the writer FileStream.

    var tempFile = Path.GetTempFileName();
    using var writer = File.OpenWrite(tempFile);

    var client = new RestClient("https://provider-api.spotify.com/v1/analytics");
    var request = new RestRequest("{licensor}/enhanced/tracks/{year}/{month}/{day}", DataFormat.Json)
            .AddUrlSegment("licensor", "licensor_name")
            .AddUrlSegment("year", "2021")
            .AddUrlSegment("month", "1")
            .AddUrlSegment("day", "10");
    
    spotifyRequest.AddHeader("Authorization", $@"Bearer {token}");
    var checkResponse = spotifyClient.Get<SpotifyTracksResourceModel>(spotifyRequest);

    request.ResponseWriter = responseStream =>
    {
        using (responseStream)
        {
            responseStream.CopyTo(writer);
        }
    };
    var response = client.DownloadData(request);
    writer.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM