繁体   English   中英

Azure Web服务:从单个Web窗体调用多个Web服务

[英]Azure Web Service: Calling Multiple web services from a single webform

总而言之,

  • VS 2015社区
  • SQL Express 2016
  • Azure机器学习
  • Azure Web服务

处理流程:

用户从下拉列表中输入特定的数据,此数据用作参数,以调用DB上的存储过程,该存储过程将数据返回到gridview(被发送到gridview以进行测试),然后将该数据传递给Azure机器学习webservice并返回/显示Web服务预测。

我让它为一种服务(invokeResponseServiceFT)工作,但最终目标是让7个服务全部从同一网页运行(因为它们都使用相同的参数,对于最终用户而言,这不应是表格的重载)。

现在添加第二个服务时出现了问题,调用它时我收到此错误:

“ StatusCode:400,ReasonPhrase:“错误请求”,版本:1.1,内容:System.Net.Http.StreamContent,标头:{x-ms-request-id:fa6ae7d9-63c9-48ee-bf8a-c455838d905d日期: 2017年2月12日11:05:41 GMT ETag:“ db595771cdbd434aa2a92609518f0aad”服务器:Microsoft-HTTPAPI / 2.0内容长度:319内容类型:application / json; charset = utf-8}“

我已经仔细检查了发布网址和api键是否正确。 Json的结构完全相同,因此只需要从第一个服务中重用即可。 关于这个问题有一点损失。 任何想法将不胜感激!

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
            {

            }
        }
    }
}

解决了

在为json请求的特定列分配值时,我使用了其中一个列名进行了错字操作。 “ ...至少可以讨厌!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM