2017-02-12 5 views
0

Итак, подведем итог,Azure Web Service: Вызов нескольких веб-сервисов от одного веб-формы

  • VS 2015 сообщество
  • SQL Express 2016
  • Azure Machine Learning
  • Azure Webservice

Технологический поток:

Пользователь inp uts конкретных данных из выпадающих списков. Эти данные используются в качестве параметров для вызова хранимой процедуры в БД, которая возвращает данные в gridview (отправляется в gridview для целей тестирования), эти данные затем передаются на веб-сервис обучения Azure Machine и возвращает/отображает прогноз веб-сервисов.

У меня есть работа для одной службы (invokeResponseServiceFT), но конечная цель состоит в том, чтобы все 7 служб работали с одной и той же веб-страницы (поскольку все они используют одни и те же параметры, это не должно быть перегрузкой форм для конечных пользователей).

Теперь проблема возникла при добавлении второго сервиса, я получаю эту ошибку, когда она называется:

«StatusCode: 400, ReasonPhrase: 'Bad Request', версия: 1.1, Содержание: System.Net.Http.StreamContent, заголовки: {X-MS-запрос-ID: fa6ae7d9-63c9-48ee-bf8a-c455838d905d Дата: Вс, 12 Февраль 2017 11:05:41 GMT ETag: "db595771cdbd434aa2a92609518f0aad" Сервер : Microsoft-HTTPAPI/2.0 Content-Length: 319 Content-Type: application/json; charset = utf-8} "

Я дважды проверил URL-адрес сообщения, и ключ api оба были правильными. Структура Json точно такая же, что и повторное использование с 1-го сервиса. Небольшая потеря относительно проблемы. Любые идеи будут высоко оценены!

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.IO; 
using System.Net.Http; 
using System.Net.Http.Formatting; 
using System.Net.Http.Headers; 
using System.Text; 
using System.Threading.Tasks; 
using Newtonsoft.Json; 
using System.Web.Script.Serialization; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     /// string connectionString = SqlDataSource1.ConnectionString; 
    } 

//json structure 

    public class Rootobject 
    { 
     public Results Results { get; set; } 
    } 

    public class Results 
    { 
     public Output1 output1 { get; set; } 
    } 

    public class Output1 
    { 
     public string type { get; set; } 
     public Value value { get; set; } 
    } 

    public class Value 
    { 
     public string[] ColumnNames { get; set; } 
     public string[] ColumnTypes { get; set; } 
     public string[][] Values { get; set; } 
    } 

    // Start of Azure Machine Learning web service 
    public class StringTable 
    { 
     public string[] ColumnNames { get; set; } 
     public string[,] Values { get; set; } 
    } 

    // public keyword added in front of async 
    // "string[] inputparams, Label label" added to function 
    public async Task InvokeRequestResponseServiceFT(string[] inputparams, Label label) 
    { 
     using (var client = new HttpClient()) 
     { 
      var scoreRequest = new 
      { 
       Inputs = new Dictionary<string, StringTable>() { 
         { 
          "input1", 
          new StringTable() 
          { 
           ColumnNames = new string[] {"Venue", "TeamA", "TeamB", "TP", "AHT12", "BHT12", "SPFT12", "SPHT12", "SP2HT12", "GFT12", "GHT12", "G2HT12", "GFT", "GHT", "G2HT", "SPFT", "SPHT", "SP2HT", "AFT", "BFT", "AHT", "BHT", "AVGFT"}, 
      // test data Values = new string[,] { { "Glasgow", "Glasgow", "Leinster", "85", "85", "85", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21" }, } 
           Values = new string[,] { { inputparams[0], inputparams[1], inputparams[2], inputparams[3], inputparams[4], inputparams[5],inputparams[6],inputparams[7],inputparams[8],inputparams[9],inputparams[10],inputparams[11],inputparams[12],inputparams[13],inputparams[14],inputparams[15],inputparams[16],inputparams[17],inputparams[18],inputparams[19],inputparams[20],inputparams[21],inputparams[22] }, } 
          } 
         }, 
        }, 
       GlobalParameters = new Dictionary<string, string>() 
       { 
       } 
      }; 
      // 3. TO DO: Update apiKey 
      const string apiKey = "api key"; // Replace this with the API key for the web service 
      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); 

      // 4. TO DO: Replace following line client.BaseAddress with the corresponding from web service 
      client.BaseAddress = new Uri("post address"); 

      // ".ConfigureAwait(false)" appended to call as we are calling this function from UI 
      HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false); 

      if (response.IsSuccessStatusCode) 
      { 
       string result = await response.Content.ReadAsStringAsync(); 

       // The following lines were added: 
       JavaScriptSerializer ser = new JavaScriptSerializer(); 

       // This deserialization will only work if the corresponding C# classes are defined for JSON. 
       Rootobject myresults = ser.Deserialize<Rootobject>(result); 

       var score = myresults.Results.output1.value.Values; //from C# classes defined above from JSON output 

       string scoredlabels = score[0][0]; 
       string scoredprobabilities = score[0][23]; 

       ResultsLabel.Text = scoredprobabilities; 
      } 
      else 
      { 
       ResultsLabel.Text = "the script hasn't worked"; 
      } 
     } 
    } 

    /// <summary> 
    /// ////HT JSON 
    /// </summary> 

    // public keyword added in front of async 
    // "string[] inputparams, Label label" added to function 
    public async Task InvokeRequestResponseServiceHT(string[] inputparams, Label label) 
    { 
     using (var client = new HttpClient()) 
     { 
      var scoreRequest = new 
      { 
       Inputs = new Dictionary<string, StringTable>() { 
         { 
          "input1", 
          new StringTable() 
          { 
           ColumnNames = new string[] {"Venue", "TeamA", "TeamB", "TP", "AHT12", "BHT12", "SPFT12", "SPHT12", "SP2HT12", "GFT12", "GHT12", "G2HT12", "GFT", "GHT", "G2HT", "SPFT", "SPHT", "SP2HT", "AFT", "BFT", "AHT", "BHT", "AVGFT"}, 
      //Test Data Values = new string[,] { { "Glasgow", "Glasgow", "Leinster", "85", "85", "85", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21", "21" }, } 
           Values = new string[,] { { inputparams[0], inputparams[1], inputparams[2], inputparams[3], inputparams[4], inputparams[5],inputparams[6],inputparams[7],inputparams[8],inputparams[9],inputparams[10],inputparams[11],inputparams[12],inputparams[13],inputparams[14],inputparams[15],inputparams[16],inputparams[17],inputparams[18],inputparams[19],inputparams[20],inputparams[21],inputparams[22] }, } 
          } 
         }, 
        }, 
       GlobalParameters = new Dictionary<string, string>() 
       { 
       } 
      }; 
      // 3. TO DO: Update apiKey using value from your web service on Machine Learning portal 
      const string apiKey = "api key"; // Replace this with the API key for the web service 
      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); 

      // 4. TO DO: Replace following line client.BaseAddress with the corresponding one from web service 
      client.BaseAddress = new Uri("////post address "); 

      // ".ConfigureAwait(false)" appended to call as we are calling this function from UI 
      HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false); 

      if (response.IsSuccessStatusCode) 
      { 
       string result = await response.Content.ReadAsStringAsync(); 

       JavaScriptSerializer ser = new JavaScriptSerializer(); 

       // deserialization 
       Rootobject myresults = ser.Deserialize<Rootobject>(result); 

       var score = myresults.Results.output1.value.Values; //from C# classes defined above from JSON output 

       string scoredlabels = score[0][0]; 
       string scoredprobabilities = score[0][23]; 

       // 5. TO DO: format the return value 
       ResultsHT.Text = scoredprobabilities; 
      } 
      else 
      { 
       // Request was not successful - could be incorrect APIKey, missing values, etc... 
       ResultsHT.Text = "the script hasn't worked";//response.ToString(); 
      } 
     } 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     //Create a using statement to handle your Connection 
     using (SqlConnection sqlConnection = new SqlConnection(SqlDataSource1.ConnectionString)) 
     { 
      //Open your connection 
      sqlConnection.Open(); 

      //Build your Command (and denote it is a stored procedure) 
      SqlCommand sqlCommand = new SqlCommand("Getdetails", sqlConnection); 
      sqlCommand.CommandType = CommandType.StoredProcedure; 

      //Add your parameters (assuming they are defined the same within your Stored Procedure 
      sqlCommand.Parameters.AddWithValue("@Venue", DDVenue.Text); 
      sqlCommand.Parameters.AddWithValue("@TeamA", DDTeamA.Text); 
      sqlCommand.Parameters.AddWithValue("@TeamB", DDTeamB.Text); 

      try 
      { 
       DataSet DS = new DataSet(); 
       //Just execute the Query directly 
       sqlCommand.ExecuteNonQuery(); 
       SqlDataAdapter da = new SqlDataAdapter(sqlCommand); 
       da.Fill(DS); 
       GridView1.DataSource = DS; 
       GridView1.DataBind(); 
       string[] inputparams = new string[DS.Tables[0].Columns.Count]; 

       for (int col = 0; col < DS.Tables[0].Columns.Count; ++col) 
       { 
        inputparams[col] = DS.Tables[0].Rows[0][col].ToString(); 
       } 
       InvokeRequestResponseServiceFT(inputparams, ResultsLabel).Wait(); 
       InvokeRequestResponseServiceHT(inputparams, ResultsHT).Wait(); 
       // Clear(); 
      } 
      catch 
      { 

      } 
     } 
    } 
} 

ответ

0

решаемые его,

При присвоении значения для определенных столбцов для запроса JSon, я сделал опечатку с одним из имен столбцов .... поэтому в методе InvokeRequestResponseServiceHT, одной из колонн был назван «TP», где он должен был быть «HTP» ... раздражающим, если не сказать больше!