简体   繁体   中英

No response while calling API in ASP.NET C# Web Forms

I have been searching this forum and others to resolve a seemingly simple problem. The objective is to call 2 APIs and make some calculations on the data received. However, when I am calling any API from my code below, there is no response to the PostAsJsonAsync call. Debugging shows that the command is executed but the code after this call is never executed. I do get the following messages in the Chrome developer tool.

'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-2-130904674774978518): Loaded 'C:\\Users\\ADMIN\\AppData\\Local\\Temp\\Temporary ASP.NET Files\\vs\\6d7d5266\\5b17a55b\\App_Web_vu1twtot.dll'. Cannot find or open the PDB file. 'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-2-130904674774978518): Loaded 'C:\\Users\\ADMIN\\AppData\\Local\\Temp\\Temporary ASP.NET Files\\vs\\6d7d5266\\5b17a55b\\App_Web_h35301am.dll'.

The thread 0x3b1c has exited with code 0 (0x0). The thread 0x34a4 has exited with code 0 (0x0).

The API being used is a simple fake API from http://jsonplaceholder.typicode.com/ . This API and others I have tested respond fine if I use Ajax in JS. Please help me out.

The code below is taken from an ASP.NET tutorial at http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class Product
{
    public double userid { get; set; }
    public double id { get; set; }
    public string title { get; set; }
    public string body { get; set; }
}

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // HTTP POST
            var gizmo = new Product() { userid = 11, id = 100, title = "Widget11", body = "Widget11" };
            HttpResponseMessage response = await client.PostAsJsonAsync("/posts/1", gizmo);
            if (response.IsSuccessStatusCode)
            {

            }

        }
    }

}

Check this

I was having similar issues because of too many async method.

I'm not much into web forms but I have tried it in WPF Application!

Use the following button in MainWindow.xaml:

<Grid>
    <Button Name='api_btn' Click="api_btn_Click">Call Api</Button>
</Grid>

Paste the following code in MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ApiTest
{
    public class Description
    {
        public int id { get; set; }
        public int userId { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void api_btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //HttpsPostRequest(URL);
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                    Description desc = null;
                    var response = await client.GetAsync("posts/1").ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        desc = await response.Content.ReadAsAsync<Description>();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception caught.", ex);
                //throw;
            }
        }
    }
}

I had the same problem, and I resolved this. Attention to this issue, you have a Async method that name is "RunAsync". and in to this method, you called PostAsJsonAsync as Async.

if you use nesting Async method, probably you'll have "DeadLock" in your result. to prevent of this issue, at the end of the second,3rd and more than async method use "ConfigureAwait(false)" for instance :

public static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP POST
        var gizmo = new Product() { userid = 11, id = 100, title = "Widget11", body = "Widget11" };
        HttpResponseMessage response = await client.PostAsJsonAsync("/posts/1", gizmo).ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {

        }

    }

This works properly.

HttpResponseMessage response = await client.PostAsJsonAsync("/posts/1", gizmo).ConfigureAwait(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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