目前Azure ML 生成的web service如果通过前端直接ajax的话,会出现跨域400错,所以我们需要一个后台桥梁,
先访问后端桥梁,再访问Azure ML 的webservice
$.ajax({
type: "POST",
url: "../api/Values/post1",
data: { "": $("#cv").val() },
dataType: "json",
success: function (data) {
console.log(data);
alert(data);
layer.close(index);
},
error: function (xhr, state, errorThrown) {
requesFail(xhr);
alert("fail");
layer.close(index);
}
});
[HttpPost]
// POST api/values
public Task<string> Post1([FromBody]string value)
{
return InvokeRequestResponseService(value);
}
static async Task<string> InvokeRequestResponseService(string data)
{
using (var client = new HttpClient())
{
var scoreRequest = new
{
Inputs = new Dictionary<string, StringTable>() {
{
"cv",
new StringTable()
{
ColumnNames = new string[] {"CV"},
Values = new string[,] { { data } }
}
},
},
GlobalParameters = new Dictionary<string, string>()
{
}
};
const string apiKey = "abc"; // Replace this with the API key for the web service
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri("https://abc.com");
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return result;
}
else
{
string responseContent = await response.Content.ReadAsStringAsync();
return responseContent;
}
}
}
public class StringTable
{
public string[] ColumnNames { get; set; }
public string[,] Values { get; set; }
}
如果从ASP.Net应用程序的UI线程调用此代码,则下面的“await”语句可能会导致死锁。
解决此问题的一种方法是调用ConfigureAwait(false)