lolatu
lolatu

Reputation: 101

Blazor Post and Response C#

Having an issue posting from client to server in a server-side Blazor webapp.

I've created two simple classes in a shared library:

public class CommandRequest
{
    public int RequestNumber { get; set; }
}

public class CommandResponse
{
    public int ResponseNumber { get; set; }
}

My client side code:

@if (response == null)
{
    <p>Loading...</p>
}
else
{
    <p>@response.ResponseNumber</p>
}

@functions {
    CommandResponse response;

    protected override async Task OnInitAsync()
    {
        var request = new CommandRequest() {RequestNumber = 3};
        response = await Http.SendJsonAsync<CommandResponse>(HttpMethod.Post,"api/SampleData/ProcessRequest", request);
    }
}

My server side request handler:

    [HttpPost("[action]")]
    public CommandResponse ProcessRequest(CommandRequest request)
    {
        return new CommandResponse() { ResponseNumber = request.RequestNumber * 2 };
    }

When I debug this the ProcessRequest method is always passed an empty object, request.RequestNumber is 0. I'm new to ASP.NET and Blazor, what am I doing wrong?

Upvotes: 3

Views: 4293

Answers (1)

lolatu
lolatu

Reputation: 101

Adding [FromBody] attribute to the CommandRequest parameter solved my problem:

    [HttpPost("[action]")]
    public CommandResponse ProcessRequest([FromBody] CommandRequest request)
    {
        return new CommandResponse() { ResponseNumber = request.RequestNumber * 2 };
    }

A reference here: What is the function of [FromBody] Attribute in C#?

Upvotes: 4

Related Questions