Using async/await and returning Task From ASP.NET Web API Methods

前端 未结 2 1233
花落未央
花落未央 2021-02-06 01:11

I have a Portable Class Library (PCL) method like this:

public async Task GetLineStatuses()
{
    HttpWebRequest request = (HttpWebRequest)WebReque         


        
2条回答
  •  走了就别回头了
    2021-02-06 02:05

    as alternative:

    public static async Task CallGET(string requestUri, string id = "")
    {
        string responseData;
        using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            Uri.TryCreate(new Uri(baseURI), $"{requestUri}{(string.IsNullOrEmpty(id) ? string.Empty : $"/{id}")}", out Uri fullRequestUri);
            using (var response = await client.GetAsync(fullRequestUri))
            {
                responseData = await response.Content.ReadAsStringAsync();
            }
            return responseData;
        }
    }
    

    and call would be:

    var getListUsersResult = Utils.CallGET($"/v1/users").Result;
    var resultset= JsonConvert.DeserializeObject(getListUsersResult, typeof(List)) as List;
    UserDTO r = users.Where(d => d.Name.ToLower().Contains("test")).FirstOrDefault();
    

    and another call for one item:

    var getUser = Utils.CallGET($"/v1/users", $"{USER_ID}").Result;
    var getUserResponse = JsonConvert.DeserializeObject(getUser, typeof(UserDTO)) as UserDTO;
    

提交回复
热议问题