Walkthrough: How to create an Azure CORS enabled Web API against SQL Azure and consume it from angular in 10 minutes

Want to have an end to end solution up FAST?  We’re talking full API, consumable from Angular WITH full database support built in?  What’s more, I bet you’d also like to know how to create your CRUD ops instantly right?  If this is you then read on!…

Step 1 – Create a .NET Framework API project in Visual Studio 2017:

We are going to create a .NET Framework project and not a .NET Core project. This is because the Entity Framework (EF) does not play nicely with asp.net core API projects yet. I certainly hope Microsoft will fix this in the near future but for now, since we are planning to use an EF approach to quickly set up our data retrieval, we’re going to use the conventional .NET Framework.

Step 2 – Create the database:

This is the easiest step of the whole tutorial.  Once you have created your API project, create a database in SQL Azure, then add a single table, then ensure that we can connect to it.  Here’s the steps:
1.  Open your SQL Management console in the Azure portal then click the plus button to create a new database.

2.  Grab the connection string from the database and use your favorite SQL editor to connect
3.  Create a simple person table using the script below.  

CREATE TABLE [dbo].[person] ( [Id] INT NOT NULL, [person] NVARCHAR (50) NULL, [phone] NVARCHAR (50) NULL, PRIMARY KEY CLUSTERED ([Id] ASC) );

 

Personally I prefer using the trusty old Enterprise Manager but you can also create a connection on your server Explorer tab in Visual Studio and connect from there.  From the server Explorer database node you can open up a nifty table editor that has some great features like allowing you to edit the table script alongside the more intuitive tabular user interface.  

Step 3:  Add an Entity Framework component

Right click your solution and add a new “ado.net entity data model” instance.

Run through the defaults to get a Poco class for your person table.  Once complete, double clicking the “Model1.edmx” should reveal the following class.  Now you are ready to create an API controller around the person entity.

Step 4: Create the api controller  

Creating API controllers is best done with the scaffolding feature available in Visual Studio 2017.  Simply right click your solution->add->new scaffolded item.
Then, in the wizard, select the second option which is “ web API 2 controller with actions, using Entity Framework”.


  Then select your model class and data context class and go with the default controller name. It should look something like this.

Step 5: Test locally

Now you should test locally very quickly just so you don’t have any surprises when you publish to Azure in the following steps.  Hit F5 and wait a second while the runtime fires up a browser then tries to load your endpoint.  You’ll get a 403 or 404.  I got this [pic].  Never fear, you are hosting an endpoint and the debugger just didn’t know what to load.  Simply enter the correct URL in the browser by navigating to http://localhost:/api/people.  Yes that’s correct, VS 2017 actually pluralized our person datatype to people in the get all method.  I’m impressed!

This output would look better with a few records in the database so let’s add a couple people quickly using the following update script.

INSERT [dbo].[person] ([person], [phone]) VALUES (N'Jerry', N'1234567890')
GO
INSERT [dbo].[person] ([person], [phone]) VALUES (N'Larry', N'3214567890')
GO
INSERT [dbo].[person] ([person], [phone]) VALUES (N'Susie', N'1237894560')
GO
INSERT [dbo].[person] ([person], [phone]) VALUES (N'Steve', N'3216549870')
GO
INSERT [dbo].[person] ([person], [phone]) VALUES (N'Riley', N'3219874560')
GO

 

Step 6: Deploy

Now we simply publish our service to Azure by right clicking the project->publish.  Follow the steps in the wizard.  It is pretty self explanatory.  Once the service is published, you can view it under your “app services” section.

Step 7 Enable CORS

To enable CORS, pull up the service in your Azure portal then click the CORS button

This will show you the following interface.  Add a * for now to just make sure everything works and you can pare it back later to be more secure (don’t use this approach if you are building anything more meaty than a demo app).

cors-setting

I’ve already added my * here

Step 8 Create angular base proj

Using my base bootstrap template found here on my GitHub (or any other template you like), create a simple angular 4 project to consume your new API.

Note: you can also get the entire bootstrap angular project with the below updates from my GitHub here.

 

Step 9 – Add the API consumer code

Add the following code to the app.component.ts file in order to consume the api.  Be sure to enter your own service URL.  

 

import { Component } from '@angular/core';

import { Http, Response, RequestOptions, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import  'rxjs/add/observable/of';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'basic bootstrap - app works!';


  constructor(private http: Http) { }

  getHeaders() {
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
  }

  vResults: Array<any>;

  getNew()
  {
    this.http.get("<your service URL>", { headers: this.getHeaders() })
      .map(res=>res.json())
      .subscribe(
        data=> this.vResults=data,
        err=>console.log(err),
        ()=>console.log('done')
      );
  }

  getAPI() {
    this.getNew();
  }

}

If successful, clicking the “Get API” button will get you this:

 

Then run your angular project and that’s it!  You should be able to read the CORS service from angular without seeing this:

Richard Strickland

Leave a Reply

Your email address will not be published. Required fields are marked *