【问题标题】:Posting a string to a .Net Core API [duplicate]将字符串发布到 .Net Core API [重复]
【发布时间】: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]。非常感谢您的快速响应!

标签: c# asp.net-core-webapi


【解决方案1】:

我正在使用这样的代码

   //var baseAddress = "http://localhost:55480";

    var api = "api/company/getcompany";

    client.BaseAddress = new Uri(cURI)
    var contentType = new MediaTypeWithQualityHeaderValue("application/json");
    client.DefaultRequestHeaders.Accept.Add(contentType);

    var data=new Dictionary<string, string>()
    {
      {"Company", companyName}
    };

    var content = new FormUrlEncodedContent(data);

    var response = await client.PostAsync(api, content);

    if (response.IsSuccessStatusCode)
    {
        var json = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<CompanyType>(json);
    }

【讨论】:

  • 它发布了,但在 API 中,Company 值仍然为空
  • @TheWizardOfTN 你在调试器中检查了吗?请求是否命中 API?您检查了 companyName 值吗?
  • 缺少 [FromForm]。添加时效果很好
猜你喜欢
  • 2018-09-20
  • 1970-01-01
  • 2020-03-31
  • 2021-07-18
  • 2020-12-04
  • 2020-11-01
  • 2017-02-02
  • 1970-01-01
  • 2016-08-02
相关资源
最近更新 更多