Search code examples
c#file-uploadblazorrefit

C# Refit Client via Blazor - How to upload a file?


I'm trying to use the Refit library to post a file to my backend using these instructions

But I have not been able to make this work. I found this issue which seems to indicate the same thing I'm doing, but it didn't help: https://github.com/reactiveui/refit/issues/991

//refit api

[Multipart]
[Post("/api/cluster/deploy")]
Task PostDeployAsync([AliasAs("file")] StreamPart stream);

//my backend controller
[HttpPost("deploy"), DisableRequestSizeLimit]
public async Task PostDeployAsync(IFormFile file)
{

//blazor code
<Blazorise.FileEdit Changed="@OnChanged"  />

async Task OnChanged(FileChangedEventArgs e)
{
    foreach (var file in e.Files)
    {
        var fs = file.OpenReadStream();
        await _api.PostDeployAsync(new StreamPart(fs, file.Name, "application/zip", file.Name));

In my controller the IFormFile file is null. What am I doing wrong?

Below is the method I used to verify that the refit part is the problem. With this, the file on the controller is populated correctly.

@inject HttpClient http

var fileContent =
    new StreamContent(file.OpenReadStream(maxFileSize));

fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");

using var content = new MultipartFormDataContent();
content.Add(
    content: fileContent,
    name: "\"files\"",
    fileName: file.Name);

var response =
    await http.PostAsync("api/cluster/deploy", content);

Solution

  • Looks like the problem was the last parameter to the StreamPart. I changed my controller to accept IEnumerable<IFormFile> files and then put that variable name "files" as the final parameter of the StreamPart:

    await _api.PostDeployAsync(new StreamPart(fs, file.Name, "application/zip", "files"));
    
    
    [HttpPost("deploy"), DisableRequestSizeLimit]
    public async Task PostDeployAsync(IEnumerable<IFormFile> files)