c# - c# asp.net网站调用一个webApi
问题描述
由于缺乏管理线程的经验,我遇到了一个问题。我在下面有这个动作:
public static async Task<joueurs> loadjoueurs(int id)
{
joueurs EmpInfo = new joueurs();
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri("http://www.myWebApi.fr/api/");
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("joueurs?id=" + id);
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
EmpInfo = JsonConvert.DeserializeObject<joueurs>(EmpResponse);
return EmpInfo;
}
return null;
}
它只是客户端从 webApi 获取我的数据(没有 ssl 没有身份验证,当我测试它时我收到正确的值)但是当我使用上面的函数(在我的 asp.net 网站中)拨打电话时......它永远停留在 HttpResponseMessage = await ....。
在我的 webApi 中,我有两个名称相同但参数不同的函数。
public async Task<IHttpActionResult> Getjoueur(int iduser, int idsport)
和
public async Task<IHttpActionResult> Getjoueur(int id)
所以我不知道问题出在哪里。
(续集)这是我称之为 Task 的地方:
public SuperModel(int id)
{
this.joueur = Repojoueurs.loadjoueurs(id).Result;
/* this.classificationSport = Repoclassificationsport.loadclassificationsport().Result;
...
*/
}
然后我的 Supermodel 在我的 Home 控制器中被实例化:
public ActionResult Index(int id)
{
SuperModel superModel = new SuperModel(id);
return View(superModel);
}
解决方案
您可以尝试不使用async并等待吗?大约三个变化如下
public static HttpResponseMessage loadjoueurs(int id)
{
HttpResponseMessage Res = client.GetAsync("joueurs?id=" + id);
return Request.CreateResponse(HttpStatusCode.OK,EmpInfo, "application/json");
}
推荐阅读
- sql - Join Two Tables based on a range of dates
- javascript - HTML / D3.js - 如何从鼠标光标而不是左上角缩放
- user-interface - Katalon Studio 中录制的脚本的播放问题
- sql - SQL Inner join into counting distinct
- python - ValueError:无法将输入数组从形状(10,1)广播到形状(10)
- python - 有没有办法简化这个 python 代码?
- c++ - 如何将输出数字分为奇数和偶数?
- python - 如何使用 boto3 获取用户的当前密码年龄
- java - 访问 getter 是私有的类的字段
- c++ - 打印所有 A 链表的元素 (C++)