简体   繁体   English

在ASP.NET C#Web窗体中调用API时无响应

[英]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. 目的是调用2个API,并对接收到的数据进行一些计算。 However, when I am calling any API from my code below, there is no response to the PostAsJsonAsync call. 但是,当我从下面的代码调用任何API时,对PostAsJsonAsync调用没有响应。 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. 我确实在Chrome开发者工具中收到以下消息。

'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'. 'iisexpress.exe'(CLR v4.0.30319:/ LM / W3SVC / 2 / ROOT-2-130904674774978518):已加载'C:\\ Users \\ ADMIN \\ AppData \\ Local \\ Temp \\ Temporary ASP.NET Files \\ vs \\ 6d7d5266 \\ 5b17a55b \\ App_Web_vu1twtot.dll”。 Cannot find or open the PDB file. 找不到或打开PDB文件。 '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'. 'iisexpress.exe'(CLR v4.0.30319:/ LM / W3SVC / 2 / ROOT-2-130904674774978518):已加载'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). 线程0x3b1c已退出,代码为0(0x0)。 The thread 0x34a4 has exited with code 0 (0x0). 线程0x34a4已退出,代码为0(0x0)。

The API being used is a simple fake API from http://jsonplaceholder.typicode.com/ . 使用的API是来自http://jsonplaceholder.typicode.com/的简单伪造API。 This API and others I have tested respond fine if I use Ajax in JS. 如果我在JS中使用Ajax,则该API和我测试过的其他API都会很好地响应。 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 以下代码取自http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client上的ASP.NET教程

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! 我不太喜欢Web表单,但是我已经在WPF应用程序中尝试过它!

Use the following button in MainWindow.xaml: 使用MainWindow.xaml中的以下按钮:

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

Paste the following code in MainWindow.xaml.cs: 将以下代码粘贴到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". 注意此问题,您有一个名为“ RunAsync”的异步方法。 and in to this method, you called PostAsJsonAsync as Async. 在此方法中,您将PostAsJsonAsync称为Async。

if you use nesting Async method, probably you'll have "DeadLock" in your result. 如果您使用嵌套异步方法,则结果中可能会有“ DeadLock”。 to prevent of this issue, at the end of the second,3rd and more than async method use "ConfigureAwait(false)" for instance : 为避免此问题,在第二,第三和更多种异步方法的末尾,例如使用“ ConfigureAwait(false)”:

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); HttpResponseMessage response =等待客户端。PostAsJsonAsync(“ / posts / 1”,gizmo).ConfigureAwait(false);

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

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