Calling an Azure Machine Learning Web Service from a web page

Learn how to create and publish a web site to consume an Azure Machine Learning web service in less than 30 minutes. You do not need any coding experience with this guide.

We assume that you have an Azure Machine Learning experiment and that you published it as a predictive web service.

We also assume that you have Visual Studio 2015 Community Edition installed and we invite you to go through the earlier post to make sure you know how to copy the correct C# sample code from the Machine Learning portal, and know where to find the API Key and RequestURI.

In this post, we will create a web page and call an Azure Machine Learning web service from a button on that web page.

Create a Web Application in Visual Studio.

Under the File menu in Visual Studio, Click on New and then Project.

Expand Visual C#, select Web and in middle pane select ASP.NET Web Application. In the bottom pane name your application or leave the existing name of WebApplication1 if this is your first project. You may want to uncheck “Add application Insights”. Below Application Insights – if you already have an Azure subscription -, enter your Azure credentials and select the Azure subscription that will be used if you decide to publish your web site.   ”Create directory for solution” should be checked but “Create new Git repository” does not need to be checked. Click OK.

You need now to select a particular template:


Select Web Forms. In Add folders and core references, do NOT select Web API (leave the default checkboxes). We will need to add the Web API Reference by using the NuGet Package Manager later.

Click on Change Authentication and select No authentication as this is a demo.

If you have a Microsoft Azure subscription, leave the “Host in the cloud” checkbox enabled so you can share your experiment with others, otherwise uncheck it for testing the web page locally. (Do yourself a favor and get a trial Azure subscription to see how easy it is to publish a web site.)

Click OK to create your project. This will take about 30 seconds.

If you elected to publish to Microsoft Azure, you will see this dialog box:


Give your web site a name, select a subscription, and select Create New if you have no existing Service Plan or Resource Group. You do not need a database so make sure No database is selected and click Ok.

Note on service reference:

An Azure Machine Learning web service is a REST service. There is no need to add a service reference (or connected service) in Visual Studio in order to access a ML web service because with REST, there is no service definition page, unlike WCF or ASMX. You just call the Azure Machine Learning REST web service from your code after installing a NuGet package:

In Visual Studio, click on Tools menu, then on Nuget Package Manager, and then on Package Manager Console.

You will get in the bottom window a PM prompt such as PM>


Install-Package Microsoft.AspNet.WebApi.Client

And press Enter.

In this new project, let’s delete the existing Default.aspx form and we will recreate it from scratch.

In solution Explorer, right-click on Default.aspx and click Delete:


Type CTRL-SHIFT-A to add a new item (or right-click on your project name in Solution Explorer, click on Add, and click New Item).  Select Web Form, name it Default.aspx and click Add.


Double-click on Default.aspx to open it.  Click on the ”Source” tab.

Copy the text in this page:

and insert it where you see “insert code here”.


The code should look like this.


This is a form with three fields (two textboxes and one listbox) and a submit button. This is an example form. Your experiment may have more or less fields. Click on Design to continue inserting additional fields based on the parameters you need to send to your Azure Machine Learning web service. This form looks like this when you click on the Design tab:


Open the Azure Machine Learning portal

Sign-in to Azure Machine Learning Studio, click Web Services, double-click on the web service you want to consume.

Here is what we see in our Azure Machine Learning experiment. Yours will be different of course.

This ML experiment is simple: based on the aggregate average score of a set of self-tests, the number of distinct self-tests studied (in this case a maximum of five) and the total number of times these self-tests were done by students, predict whether the students will pass or fail a final exam. The experiment was trained on historical data.

Training experiment:


This experiment was published as a predictive web service. Two “Project Columns” actions were added in the predictive experiment pane to specify the columns we wanted to pass to the web service and the columns we wanted in return. Note that the default schema/behavior is to return all the columns in the original dataset + the predictions.

Be aware that the free tier sets by default a maximum of 20 concurrent executions but this can be increased to a maximum of 200. In order to change this value, open your Machine Learning Workspace, click on Web Services tab, double-click on your web service, double-click on your default endpoint, click on Configure tab, change maximum of concurrent executions and click on Save button.


Here is the schema of this ML web service (Web Service Groups – double-click on Web Service – Configuration)

Output columns were renamed to Outcome and Probability.


We need two additional pieces of information: the API Key and the C# code sample

Click on Dashboard, and copy the API key: (save it in notepad)


Verify that your web service is working by clicking on the Test button.

Enter the values for your experiment in the dialog box and click the check mark. Look in the bottom (black) ribbon for a result. If you do not get a result, you need to re-run/fix your experiment. If successful, you will see something like:

‘Experiment created on ?4?/?1?/?2016 [Predictive Exp.]’ test returned [“1″,”0.943256258964539”]…
Click on Details
You can see the Json that will be returned to your application when you call your ML web service.


Make a copy of this Json output and save it as well in notepad.

For this experiment, the Json returned is:

{“Results”:{“output1”:{“type”:”table”,”value”:{“ColumnNames”:[“Scored Labels”,”Scored Probabilities”],”ColumnTypes”:[“Int32″,”Double”],”Values”:[[“1″,”0.943256258964539”]]}}}}

To find the request URI, under API HELP PAGE, click on Request/Response


In displayed web page, navigate down to Sample Code, select C#, click on Select Sample code, right-click and click Copy. Save it in a notepad file. You will need to get values such as list of parameters, and RequestURI.

At this stage, you should have located the following items from your web service:

APIKey similar to: Xvf0NZ1H……..sJUCPqZxEqvp0IfFcmg==

ColumnNames = new string[] {“Average”, “Attempts”, “Exams”},

client.BaseAddress = new Uri(“”);

Insert code for consuming the ML web service

Click on the arrow to the left of Default.aspx to expand it and double-click on Default.aspx.cs file to open it.


We need to add some “using” directives. Locate the place indicated by “insert additional “using” directives here” and add the following “using” directives:

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Web.Script.Serialization;


Since the Azure Machine Learning web service returns a JSON file, let’s add the corresponding C# classes from this file:

at location indicated by “Insert code here” in this picture:


The page will look like the picture below.

Insert the modified code for a generic ML web service from this file:

at location indicated by “Insert code here – part 2”.


Apply your own parameters to the sample code

There is work you need to do because this is your own ML web service. In the code, you will see 5 TO DOs. They are:

// 1. TO DO: Copy following line from your own ML web service. You will have different column names and possibly more or less columns.
ColumnNames = new string[] {“Average”, “Attempts”, “Exams”},

Your experiment will not have columns such as Average, Attempts, etc. From your web service, copy the correct column names and replace the existing values.

// 2. TO DO: Insert additional inputparams[x] to match the number of columns in your experiment. This experiment has only 3:
Values = new string[,] {  { inputparams[0], inputparams[1], inputparams[2] },  }

// 3. TO DO: Update apiKey using value from your web service on Machine Learning portal
const string apiKey = “Xvf0N-this-apikey-is-not-a-valid-apikey-use-your-own-Z9Ww/iY2t9JosJUCPqZxEqvp0IfFcmg==”;

The above APIKey is a non-functioning apiKey.

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

The above BaseAddress   is a non-functioning RequestURI

// 5. TO DO: format the return value as you wish:

string scoredlabels = score[0][0];
string scoredprobabilities = score[0][1];
label.Text = scoredlabels == “0” ? “It is likely that you will fail the exam!” : “You have a good chance of passing the exam with a probability of ” + string.Format(“{0:P}”, Double.Parse(scoredprobabilities));

The above return value works but you may want to change its output to match your experiment.

Insert the code behind the Submit button

As indicated in the picture, locate the end of the previous function.


At this exact location, insert button code from this file:

This code creates an array of the parameters from the form, calls the Machine Learning web service. This code also passes as a second parameter the label on the form that is used to display the result.

There is a final TO DO in this code.

// 6. TO DO. Adjust parameters to match the type of input boxes you created and the number of fields you created.

// This is based on your experiment. This experiment needs only 3 values, 2 coming from 2 textboxes and one from a list box.

string[] inputparams = new string[] { TextBox1.Text, TextBox2.Text, DropDownList1.Text };

Make also sure that the order of the parameters listed in “inputparams” matches the parameter order in the web service.

The easiest way is to retrieve the schema. For this experiment,  the schema is:


Under the Build menu, click on Build <your project>. Check that there is no error. Type CTRL-F5 to run it. A temporary instance of your web site is displayed and you can test that it is working.

Under the Build menu, you can also click Publish if you selected Publish to an Azure Web Site when you created this project. In next dialog box, click on Validate Connection, make a note of the URL of your new web site (Destination URL), and click Publish. Your web site will be published in the free tier and will be available immediately. The default form you created will be the first page you see when you access your web site.

This concludes this post: how to create and publish a web site to consume your Machine Learning web service in less than 30 minutes.

One Response

  1. Michael April 17, 2017 Reply

Leave a Reply