简体   繁体   English

ASP.Net Forms HttpClient PostAsync 无响应,无错误消息

[英]ASP.Net Forms HttpClient PostAsync no response, no error message

I have this code:我有这个代码:

using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
        {
            {"site_id","001"},
            {"apikey","abc01201az1024"},
            {"trans_id","45364136"},
        };

    // Get the parameters in the url encoded format
    var content = new FormUrlEncodedContent(values);

    //Send request
    var response = await client.PostAsync(url, content);

  DataRoot<Transaction> outPut = null;
                if (response.IsSuccessStatusCode)
                {
                    //Get Response
                    var result = await response.Content.ReadAsStringAsync();
                    JsonConvert.DeserializeObject<DataRoot<Transaction>>(result);
                }

                return outPut;
}

In the debug mode at this stage, the code does not produce any response, no error code but stops running:在此阶段的调试模式下,代码不产生任何响应,没有错误代码但停止运行:

//Send request
var response = await client.PostAsync(url, content);

there could be a better way but this solved my problem.可能有更好的方法,但这解决了我的问题。 Call your method from another one using wait:-使用等待从另一个方法调用您的方法:-

    public static async Task<string> AuthenticateUser()
    {
        var t = Task.Run(() => ClassObject.AuthenticateUser("me"));
        t.Wait();

        Console.WriteLine(t.Result);
        Console.ReadLine();
        return "ok";
    }

Using await like this, can end up in a deadlock.像这样使用 await 可能会陷入僵局。

You can use ConfigureAwait(false) in async methods for preventing such a deadlock.您可以在异步方法中使用ConfigureAwait(false)来防止这种死锁。

Update code to:将代码更新为:

var response = await client.PostAsync(url, content).ConfigureAwait(false);

This will solve the issue.这将解决问题。

Are you sure that it isn't actually returning the response and continuing execution?您确定它实际上没有返回响应并继续执行吗? Because the client.PostAsync() call is awaited execution may continue on a different thread.因为 client.PostAsync() 调用被等待执行可能会在不同的线程上继续。 Therefore, if you're just debugging line by line (via F10 or similar) it may appear that the method never returns;因此,如果您只是逐行调试(通过 F10 或类似方式),则该方法可能永远不会返回; in actuality the entire method has finished execution and your program is running.实际上,整个方法已经执行完毕,您的程序正在运行。

You may need to add another breakpoint in the method (after the PostAsync method call).您可能需要在方法中添加另一个断点(在 PostAsync 方法调用之后)。 When the PostAsync method returns on a different thread, your debugger should hit the next breakpoint.当 PostAsync 方法在不同的线程上返回时,您的调试器应该命中下一个断点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM