从HttpResponseMessage读取字符串

时间:2018-08-27 08:56:27

标签: c# string httpresponsemessage

我正在尝试从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;
    }

}            

1 个答案:

答案 0 :(得分:0)

。您不应该使用的结果。它可能会导致死锁。同样,您从api返回字符串作为响应。结果应该是字符串而不是List。我希望这会有所帮助。

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;
}