我正在尝试将POST
的值ASP NET Core Controller
。
Controller
不断获得null
的值,我不明白为什么。
发送请求
string uri = "/api/create";
//some POCO--not important
CampaignRequest<CreateCampaignParams> req = new
CampaignRequest<CreateCampaignParams> { Data = campaignParams, Ticket = this.ticket };
var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8, "application/json");
var response = await this.http.PostAsync(uri, content);
接收器
[HttpPost]
[Route("api/create")]
public async Task<long> CreateAsync([FromBody]CampaignRequest<CreateCampaignParams>pars)
{
//--- the received argument is null...i have tried putting as a string argument to no avail
try
{
var client = new CampaignClient(uri,pars.Ticket.Value);
long rez=await client.CreateCampaignAsync(pars.Data);
return rez;
}
catch (Exception)
{
return 0;
}
}
我尝试将Controller
方法的参数设置为字符串,然后反序列化。仍然字符串为空。
如何在控制器中检索StringContent
?
答案 0 :(得分:1)
最可能的原因是模型绑定错误。
要对此进行检查,请按如下所示修改您的控制器方法:
[HttpPost]
[Route("api/create")]
public async Task<long> CreateAsync([FromBody]CampaignRequest<CreateCampaignParams> pars)
{
var errorCount = ModelState.ErrorCount;
并在该errorCount行上设置一个断点,如果计数> 0,则进一步检查ModelState对象是否存在特定错误。
此外,您确定您的POST请求已使用F12浏览器工具将对象正确添加到主体中。如果不确定,请附上截图。