简体   繁体   中英

Read string from HttpResponseMessage

I am trying to read string from my HttpResponseMessage. This is my controller.

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

Its returning number in string format. How do I read that string on my form?

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

}            

.Result you should not use. It may couse deadlock. Also you return string as response from api, hence; you should get string as a result not List. I hope this helps.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM