0

I'm working on a Blazor WASM project, and I have a page that needs to post a file to the server. So I wrote something like this:

@page "/Test"
@inject HttpClient httpClient

<h4>Please upload a file.</h4>

<form>
    <InputFile OnChange="OnInputFileChange"/>
</form>

@code {

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        // Returns 1 just fine
        var dummyTest = await httpClient.GetFromJsonAsync<int>("api/Test/Action");

        // Gets a 404 error
        var response = await httpClient.PostAsJsonAsync("api/Test/Action", e.File);
        var content = await response.Content.ReadFromJsonAsync<int>();
    }
}

and I have this controller

[ApiController]
[Route("api/[controller]/[action]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<int>> Action()
    {
        return 1;
    }

    [HttpPost]
    public async Task<ActionResult<int>> Action(IFormFile file)
    {
        return 1;
    }
}

My issue is that the GET request executes just fine and dummyTest is set to 1, but response gets a 404 and trying to call ReadFromJsonAsync gives System.Text.Json.JsonException: The input does not contain any JSON tokens..

I'm not sure what I'm missing here.

Thanks in advance!

1
  • It looks like the controller isn't mapping your call to the correct method. Probably because e.File is an object and you're expecting an interface. You almost certainly need to stick to passing concrete classes. Cast e.File to myfileclass in your caller method and expect myfileclass in your controller. Commented Dec 9, 2021 at 8:55

1 Answer 1

0

In Blazor I have found so far that you need to have a JWT or alternative for server and client to communicate with each other.

In the Blazor.Client project you have an option to remove the following from the program.cs

Note that removing below is not secure, and I am unsure of the consequences of removing it. Otherwise you have to implement some kind of auth provider, I used auth0 to resolve this.

builder.Services.AddHttpClient("BlazorExample.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
    //remove this: .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.