3

在服务器端 Blazor Web 应用程序中从客户端发布到服务器时出现问题。

我在共享库中创建了两个简单的类:

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

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

我的客户端代码:

@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);
    }
}

我的服务器端请求处理程序:

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

当我调试这个时,ProcessRequest 方法总是传递一个空对象,request.RequestNumber 为 0。我是 ASP.NET 和 Blazor 的新手,我做错了什么?

4

1 回答 1

4

将 [FromBody] 属性添加到 CommandRequest 参数解决了我的问题:

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

此处参考: C#中[FromBody]属性的作用是什么?

于 2019-03-18T21:30:49.167 回答