重新分解异步获取api请求不等待数据。

编程入门 行业动态 更新时间:2024-10-08 18:31:24
本文介绍了重新分解异步获取api请求不等待数据。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好我/女孩我有点问题。我有一个执行get请求的方法。这种方法有效。所以我重新考虑了这个方法,以便某些部分可以用于其他方法。

Hello guys/girls i am having a bit of problem. i have a method that performs a get request. this method works. so i re-factored the method, so that certain parts can be used for other methods.

//Original Method public async Task<T> GetByIdAsync(T returnType, T1 controllerName, T2 Id) { var url = baseUrl + controllerName + "/" + Id; var result = returnType; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var data = response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject(data.Result); } } } //refactored method public async Task<T> GetByIdAsync<T, T1, T2>(T returnType, T1 controllerName, T2 Id) { var url = baseUrl + controllerName + "/" + Id; var result = returnType; var client = GetClient(url); var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var data = response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject<T>(data.Result); } return result; } public static HttpClient GetClient(string url) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); return client; } }

重新计算方法后,它不再等待。怎么了 ? 。 我的尝试: 原始代码有效,我试图理解为什么重新分解的代码不起作用

After i re-factored the method, it no longer awaits. what is wrong ? . What I have tried: the original code works, i am trying to understand why the re-factored code doesn't work

推荐答案

使用在对象离开使用上下文时处理(销毁)对象,所以你的HttpClient在GetClient方法之外不可用。删除使用 "using" disposes (destroys) an object when it leaves the using context, so your HttpClient is not usable outside of the GetClient method. Remove the "using" public static HttpClient GetClient(string url) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); return client; }

更多推荐

重新分解异步获取api请求不等待数据。

本文发布于:2023-11-26 10:29:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分解   数据   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!