为什么HttpClient.Post方法没有执行所有方法?

时间:2019-02-06 13:17:24

标签: c# asp.net-mvc asp.net-web-api

在这里我写了一些小函数

 public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
//Here im Calling one Private Methode 
      GetValiedSession("22");
if(1==1{
}
else
//SomeCode

GetValiedSession

 public async Task<bool> GetValiedSession(string _SesToken)
        {
            string Baseurl = WebConfigurationManager.AppSettings["Baseurl"];
            var values = new Dictionary<string, string>{
          { "securityToken","_SesToken"},
                          };
       using (var client = new HttpClient())
            {
        var _json = JsonConvert.SerializeObject(values);
 var content = new StringContent(_json, Encoding.UTF8, "application/json");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.PostAsync(Baseurl + "validate/session", content);
                var responseString = await response.Content.ReadAsStringAsync();
                return false;
            }

上述代码

var response = await client.PostAsync(Baseurl + "validate/session", content);

此代码后,其执行if(1==1){---}

请指导我如何停止该操作,直到执行为止。

1 个答案:

答案 0 :(得分:1)

将Sync方法转换为async(如果需要)(这意味着您需要更改基本方法)并将更改GetValiedSession("22");更改为await GetValiedSession("22");

public override async Task OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{

    //Here im Calling one Private Methode 
    await GetValiedSession("22");
    if(1==1{
    }
    else
    //SomeCode

}

或简单地同步使用您的方法

GetValiedSession("22").GetAwaiter().GetResult();
相关问题