为什么即使从服务器端成功验证后我也无法获得HttpResposnseMessage?

时间:2016-02-15 05:18:41

标签: c# asp.net rest asp.net-web-api httpresponse

我正在实施RESTful服务(asp.net web api 2.0)以在Webforms中执行身份验证。从我的客户端(Webforms)我生成一个令牌并将其发送到服务器端(Webapi控制器)进行验证。

Webform codeBehind file:

static async Task RunAsync(string token)
    {
        HttpClientHandler handler = new HttpClientHandler();
        handler.UseDefaultCredentials = true;
        //HttpClient Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri("http://localhost:32253/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization-Token", token);
            string uri = "api/UserDetail/Authenticate";

            //The GetAsync method sends the HTTP GET request; The await keyword suspends execution until the asynchronous method completes
            HttpResponseMessage response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                //Use ReadAsAsync to deserialize the JSON. The ReadAsync method is asynchronous because the response body can be arbitrarily large.
                ValidateUserStatus success = await response.Content.ReadAsAsync<ValidateUserStatus>();
                result = "Success";
            }
        }

Serverside方法:

    [System.Web.Http.AcceptVerbs("GET")]
    [System.Web.Http.HttpGet]
    [ActionName("Authenticate")]

    public SLS.MDS.Web.Entities.Enums.ValidateUserStatus Validate()
    {
        var token = Request.Headers.GetValues("Authorization-Token").First();
        //string decryptedData = RSAClass.Decrypt(token);
        var comparetoken = HMACSHA256Class.Hash(username, password, data);
        string[] credentials = data.Split(',');
        SLS.MDS.Web.Entities.Enums.ValidateUserStatus status = SLS.MDS.Web.Entities.Enums.ValidateUserStatus.NotSet;
        if (token == comparetoken)
        {
            if (credentials != null)
            {
                status = MDSProvider.DefaultInstance.ValidateIDSUser(credentials[0], credentials[1]);
            }
        }

        return status;
    }

服务器端验证成功并返回状态。我面临的问题是我无法在客户端(Webform)接收它。 在行,

HttpResponseMessage response = await client.GetAsync(uri);

httprequest转到服务器端并返回状态但无法接收它。原因是什么?有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

这个问题在Stack Overflow上经常出现。我建议看看这个答案,以便更好地了解发生了什么:https://stackoverflow.com/a/10351400/3299157

由于这些异步请求的性质,基本上您遇到了死锁情况。