简体   繁体   English

异步调用HttpClient以通过Ajax获取HttpResponseMessage

[英]Calling HttpClient asynchronously to get the HttpResponseMessage via ajax

I am actually trying to fetch data through a URL using the HTTPClient class. 我实际上是在尝试使用HTTPClient类通过URL获取数据。 I am calling via ajax call. 我正在通过ajax呼叫。 However, when the response is fetched it gets back into running mode from debugging mode and nothing happens. 但是,当获取响应时,它会从调试模式回到运行模式,并且什么也没有发生。 No response is retrieved. 没有检索到响应。 Below is the code: 下面是代码:

jQuery jQuery的

$.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "../../Services/AService.asmx/GetCompanyInformation",
        data: { id: JSON.stringify(id) },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async:true,
        success: function (res) {
            var options = JSON.parse(res.d);                   

        },
        error: function (errormsg) {
            $(".dropdown_SubDomainLoading").hide();
            toastr.options.timeOut = 7000;
            toastr.options.closeButton = true;
            toastr.error('Something Went Wrong');
        }
    });

WebMethod Call Web方法调用

public static string CompanyDetails;

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public string GetCompanyInformation(string id)
    {
        string authorizationKey = "Bearer 5cae498ef11f128363c1fbb2761bbab40ac0e2e5";
        string url = string.Empty;
        url = GetCompanyDetailsForApps(id);
        RunAsync(url).Wait();
        return CompanyDetails;
    }

 static async Task RunAsync(string Url)
    {
        string authorizationKey = "Bearer 5cae498ef11f128363c1fbb2761bbab40ac0e2e5";
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("Authorization", authorizationKey);
                HttpResponseMessage response = await client.GetAsync(Url);

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    //UrlMetricsResponse mozResonse = JsonConvert.DeserializeObject<UrlMetricsResponse>(content);
                    dynamic dynObj = JsonConvert.DeserializeObject(content);
                    CompanyDetails = JsonConvert.SerializeObject(dynObj);
                }

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR :" + ex.Message);
        }

    }

As soon as the client.GetAsync() function is called, it comes back to run mode and nothing is fetched. 调用client.GetAsync()函数后,它将返回运行模式,并且不会获取任何内容。 Am I doing something wrong. 难道我做错了什么。 How can i retrieve the response via the url? 如何通过网址检索响应?

Judging by [WebMethod] , I'm guessing you are maintaining a very old ASP.NET application. 通过[WebMethod]判断,我猜您正在维护一个非常旧的ASP.NET应用程序。 The problem here is incompatible libraries. 这里的问题是不兼容的库。 Old ASP.NET does not support async/await semantics, and HttpClient does not support synchronous HTTP operations. 旧的ASP.NET不支持异步/等待语义,并且HttpClient不支持同步HTTP操作。

Your best option is to upgrade the application to something more modern that supports async controllers, such as ASP.NET Web API or ASP.NET Core. 最好的选择是将应用程序升级到支持异步控制器的最新版本,例如ASP.NET Web API或ASP.NET Core。 This way you won't have to block threads on HTTP calls. 这样,您将不必在HTTP调用中阻塞线程。 But if this is not an option, you need swap out HttpClient for a library that actually supports synchronous/blocking HTTP. 但是,如果这不是一个选择,则需要将HttpClient换成实际上支持同步/阻止HTTP的库。 Have a look at WebRequest or RestSharp. 看一下WebRequest或RestSharp。 If you continue to use HttpClient and there are .Result or .Wait() calls anywhere on the call stack, you're not only blocking but you are inviting deadlocks . 如果您继续使用HttpClient,并且在调用堆栈上的任何地方都有.Result.Wait()调用,那么您不仅会阻塞,而且还会引发死锁

I can't stress this enough: HttpClient does not support synchronous HTTP , so if you can't switch to a more modern web framework, you must switch to an older HTTP library. 我对此不够强调: HttpClient不支持同步HTTP ,因此,如果无法切换到更现代的Web框架,则必须切换到较旧的HTTP库。

好吧,当我将client.GetAsync()更改为client.GetAsync().Result它起作用了。

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

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