Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 918
lolatu Avatar asked Mar 01 '26 07:03

lolatu


1 Answers

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#?

like image 177
lolatu Avatar answered Mar 03 '26 21:03

lolatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!