在服务器端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的新手,我在做什么错了?
答案 0 :(得分:3)
在CommandRequest参数中添加[FromBody]属性解决了我的问题:
[HttpPost("[action]")]
public CommandResponse ProcessRequest([FromBody] CommandRequest request)
{
return new CommandResponse() { ResponseNumber = request.RequestNumber * 2 };
}