【发布时间】:2022-01-18 04:11:35
【问题描述】:
这是我的 api 代码:
[Route("GetCompany")]
[HttpPost]
public async Task<IActionResult> ReadByCompany(string Company)
{
//this us just to verify an existing company
try
{
var entity = await _service.ReadCompanyAsync(Company, true);
return Ok(entity);
}
catch (Exception exception)
{
return BadRequest($"Error: {exception.Message}");
}
}
以及使用它的代码:
public async Task<int> GetCompany(string companyName)
{
int iRet = -1;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(cURI);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>(companyName, "Company")
});
var response = await client.PostAsync("GetCompany",content);
if (response.IsSuccessStatusCode)
{
try
{
//get the data
var _content = response.Content.ReadAsStringAsync().Result;
var company = JsonConvert.DeserializeObject<CompanyType>(_content);
if (company != null)
iRet = company.CompanyID;
}
catch (Exception ex)
{
string s = ex.Message;
}
}
}
return iRet;
}
它发布,但在 API 中显示的“公司”字符串始终为空。我已经验证它存在于“内容”变量中。我要离开什么?
【问题讨论】:
-
如果我了解 client.PostAsync 正在处理您的数据,您似乎发布的是表单,而不是正文内容。将您的帖子更改为使用正文,或者将您的 api 更改为使用 FromForm?您可以检查网络选项卡以验证它发布的内容。
-
API 中缺少 [FromForm]。非常感谢您的快速响应!