Download a file using IDownstreamApi in Microsoft.Identity.Web

370 Views Asked by At

I'm trying to download a file using IDownstreamApi I've tried the following code

    var file = await downstreamApi.GetForAppAsync<Stream>(Definitions.FileshareApi, options =>
    {
        options.RelativePath = $"{ApiPaths.FileDownload}{sourceUri}";
    }, cancellationToken: cancellationToken);
    if(file != null)
    {
        var target = new FileStream(targetFilePath, FileMode.Create);
        file.CopyTo(target);
        return true;
    }

but I get the following exception

System.Text.Json.JsonException: 'The JSON value could not be converted to System.IO.Stream. Path: $ | LineNumber: 0 |

Is it possible to download a file using the IDownstreamApi. If how do you use it to do this.

2

There are 2 best solutions below

0
Mark On BEST ANSWER

Figured it out myself:

    var response = await downstreamApi.CallApiForAppAsync(Definitions.FileshareApi, options =>
    {
        options.HttpMethod = HttpMethod.Get;
        options.RelativePath = $"{ApiPaths.FileDownload}{sourceUri}";
    }, cancellationToken: cancellationToken);
    if (response != null)
    {
        using Stream output = File.OpenWrite(Path.Combine(targetFilePath, targetFileName));
        response.Content.CopyTo(output, null, cancellationToken);
    }
1
GroM On

This method is deserializing received JSON data into this type. downstreamApi.GetForAppAsync<SomeType>(...) will just:

  1. Using GET method receive data from url
  2. Treat it as JSON content
  3. Try to deserialize this content into SomeType

So basically your code is trying to deserialize it to Stream object, which is not the same as putting content into stream.