首页 > 解决方案 > 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);
        }

标签: c#asp.netasp.net-web-apihttpclienthttpresponsemessage

解决方案


您可以尝试不使用async等待吗?大约三个变化如下

public static HttpResponseMessage loadjoueurs(int id)
    {

            HttpResponseMessage Res = client.GetAsync("joueurs?id=" + id);

return Request.CreateResponse(HttpStatusCode.OK,EmpInfo, "application/json");
     }

推荐阅读