【问题标题】:Read string from HttpResponseMessage从 HttpResponseMessage 读取字符串
【发布时间】:2018-08-27 08:56:27
【问题描述】:

我正在尝试从我的 HttpResponseMessage 中读取字符串。这是我的控制器。

[HttpGet]
[Route("api/Predracun/GetPredracunBroj/")]
public string GetPredracunBroj()
{
    string broj = "";

    List<Predracun> pred = db.Predracun.ToList();

    if (pred.Count != 0)
    {
        broj = db.Predracun.OrderByDescending(x => x.Broj).Select(x => x.Broj).First();

        int crtica = broj.IndexOf('/');
        string brSledeci = broj;

        brSledeci = broj.Substring(0, crtica);


        return brSledeci;
    }
    else
        return broj;
}

它以字符串格式返回数字。如何读取表单上的字符串?

HttpResponseMessage responseString = predracunService.GetActionResponse("GetPredracunBroj");
if (responseString.IsSuccessStatusCode)
{
    if (responseString.Content.ReadAsAsync<string>().Result != "")
    {
        List<string> brj = responseString.Content.ReadAsAsync<List<string>>().Result;
        br = brj[0];

        // br = await responseString.Content.ReadAsStringAsync(); //right!
        prvibroj = Convert.ToInt32(br);
        ++prvibroj;
    }

}            

【问题讨论】:

    标签: c# string httpresponsemessage


    【解决方案1】:

    .Result 你不应该使用。可能会导致死锁。您还返回字符串作为来自 api 的响应,因此;你应该得到字符串而不是列表。我希望这会有所帮助。

    public async Task<int> GetPredracunBroj()
    {
        int result = 0;
    
        HttpResponseMessage responseMessage = predracunService.GetActionResponse("GetPredracunBroj");
        if (responseMessage.IsSuccessStatusCode)
        {
            string responseString = await responseMessage.Content.ReadAsStringAsync();
    
            if (!int.TryParse(responseString, out result))
            {
                throw new ArgumentException($"Argument is not expected format [{responseString}]");
            }
        }
    
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2016-12-02
      • 2020-03-16
      • 1970-01-01
      相关资源
      最近更新 更多