我正在尝试使用新的 Azure 机器学习服务,并从我的模型中创建了一个 Web 服务。该服务运行正常,当我使用 HTTPS 工具向其发送 POST 请求时,我得到了预期的结果。
我的问题在于如何让我的 ASP.NET 代码与之配合。我使用了机器学习 Web 服务详细信息页面提供的代码。我知道它正确地发送了所有 POST 请求,并且 Web 服务返回了正确的 JSON,因为我在跟踪通信数据包。但不知为何,我的代码无法识别这个返回值。
我已经在 Azure 网站和 Visual Studio 中的本地站点上运行了这段代码
namespace website{ public partial class ML : Page { protected void Page_Load(object sender, EventArgs e) { InvokeRequestResponseService().Wait(); //await InvokeRequestResponseService(); } static async Task InvokeRequestResponseService() { using (var client = new HttpClient()) { ScoreData scoreData = new ScoreData() { FeatureVector = new Dictionary<string, string>() { { "age", "0" }, { "education", "0" }, { "education-num", "0" }, { "marital-status", "0" }, { "relationship", "0" }, { "race", "0" }, { "sex", "0" }, { "capital-gain", "0" }, { "capital-loss", "0" }, { "hours-per-week", "0" }, { "native-country", "0" }, }, GlobalParameters = new Dictionary<string, string>() { } }; ScoreRequest scoreRequest = new ScoreRequest() { Id = "score00001", Instance = scoreData }; const string apiKey = "dg/pwCd7zMPc57lfOSJqxP8nbtKGV7//XXXXXXXXXXXXXXXXXXXXXXXXXXXXgvdVl/7VWjqe/ixOA=="; // Replace this with the API key for the web service client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); client.BaseAddress = new Uri("https://ussouthcentral.services.XXXXXXX.net/workspaces/a932e11XXXXXXXXXXX29a69170eae9ed4/services/e8796c4382fb4XXXXXXXXXXXddac357/score"); // GETS STUCK ON THE NEXT LINE HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest); <---- NEVER RETURNS FROM THIS CALL if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); Console.WriteLine("Result: {0}", result); } else { Console.WriteLine("Failed with status code: {0}", response.StatusCode); } } } } public class ScoreData { public Dictionary<string, string> FeatureVector { get; set; } public Dictionary<string, string> GlobalParameters { get; set; } } public class ScoreRequest { public string Id { get; set; } public ScoreData Instance { get; set; } }}
回答:
这个问题是由于一个在这里讨论的错误引起的 – HttpClient.GetAsync(…) 在使用 await/async 时永远不会返回
基本上,你需要添加 ConfigureAwait(false) 方法。
所以现在这行代码看起来像这样
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false);