[英]Getting null in httpResponseMessage when calling REST API using HTTPClient
[英]Calling HttpClient asynchronously to get the HttpResponseMessage via ajax
我实际上是在尝试使用HTTPClient类通过URL获取数据。 我正在通过ajax呼叫。 但是,当获取响应时,它会从调试模式回到运行模式,并且什么也没有发生。 没有检索到响应。 下面是代码:
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');
}
});
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);
}
}
调用client.GetAsync()函数后,它将返回运行模式,并且不会获取任何内容。 难道我做错了什么。 如何通过网址检索响应?
通过[WebMethod]
判断,我猜您正在维护一个非常旧的ASP.NET应用程序。 这里的问题是不兼容的库。 旧的ASP.NET不支持异步/等待语义,并且HttpClient
不支持同步HTTP操作。
最好的选择是将应用程序升级到支持异步控制器的最新版本,例如ASP.NET Web API或ASP.NET Core。 这样,您将不必在HTTP调用中阻塞线程。 但是,如果这不是一个选择,则需要将HttpClient换成实际上支持同步/阻止HTTP的库。 看一下WebRequest或RestSharp。 如果您继续使用HttpClient,并且在调用堆栈上的任何地方都有.Result
或.Wait()
调用,那么您不仅会阻塞,而且还会引发死锁 。
我对此不够强调: HttpClient不支持同步HTTP ,因此,如果无法切换到更现代的Web框架,则必须切换到较旧的HTTP库。
好吧,当我将client.GetAsync()
更改为client.GetAsync().Result
它起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.