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

本文关键字:API 响应 调用 ASP NET C#Web 窗体 | 更新日期: 2023-09-27 18:19:38

我一直在搜索这个论坛和其他论坛来解决一个看似简单的问题。目标是调用2个API并对接收到的数据进行一些计算。然而,当我从下面的代码中调用任何API时,PostAsJsonAsync调用都没有响应。调试显示命令已执行,但此调用之后的代码从未执行。我确实在Chrome开发工具中收到了以下消息。

"iisexpress.exe"(CLR v4.0.3019:/LM/W3SSVC/2/ROOT-2-130904674774978518):已加载'C:''Users''ADMIN''AppData''Local''Temp''Temporary ASP.NETFiles''vs''6d7d5266''5b17a55b''App_Web_vu1twot.dll。找不到或无法打开PDB文件。'iisexpress.exe'(CLR v4.0.3019:/LM/W3SSVC/2/ROOT-2-130904674774978518):已加载'C:''Users''ADMIN''AppData''Local''Temp''Temporary ASP.NETFiles''vs''6d7d5266''5b17a55b''App_Web_h35301am.dll'.

线程0x3b1c已退出,代码为0(0x0)。线程0x34a4已退出,代码为0(0x0)。

正在使用的API是来自http://jsonplaceholder.typicode.com/.如果我在JS中使用Ajax,这个API和我测试过的其他API响应良好。请帮帮我。

下面的代码取自ASP.NET教程,网址为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)
            {
            }
        }
    }
}

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

检查此

由于异步方法太多,我也遇到了类似的问题。

我不太喜欢web表单,但我在WPF应用程序中尝试过!

在MainWindow.xaml中使用以下按钮:

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

在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;
            }
        }
    }
}

我遇到了同样的问题,我解决了这个问题。注意这个问题,您有一个名为"RunAsync"的Async方法。在该方法中,您将PostAsJsonAsync称为Async。

如果使用嵌套的Async方法,结果中可能会出现"DeadLock"。为了防止这个问题,在第二个、第三个和更多个异步方法的末尾使用"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)
        {
        }
    }

这可以正常工作。

HttpResponseMessage response=等待客户端。PostAsJsonAsync("/posts/1",gizmo).ConfigureAwait(false);