我正在尝试新的 Azure 机器学习服务,并根据我的模型创建了一个 Web 服务。该服务运行良好,因为当我使用 HTTPS 工具进行 POST 时,我得到了预期的结果。
我的问题是让我的 ASP.NET 代码能够使用它。我正在使用通过机器学习 Web 服务详细信息页面提供的代码。我知道它正确地发布了所有内容,并且当我对通信进行数据包跟踪时,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(...) never returns when using await/async
基本上,您需要添加ConfigureAwait(false)方法。
所以代码行现在看起来像
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false);
关于c# - 不处理 Azure ASP.NET REST Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27293645/