Part 2: Create Web API Services

In the previous tutorial, we created the initial structure of the Earnings Tracker Web API application in ASP.NET Core. In this tutorial, we will build the Web API services in Visual Studio Community 2015 Edition.

The RevenueData represents the total revenue information of a specific office versus other offices.

In Solution Explorer, right-click the EmployeeTrackerCoreRS Solution, and select Rebuild Solution to rebuild the solution.

Task 2. Create the Income data model in the EarningsTracker.Services project

The Income data model (class and interface) contains income information of an office.

In Solution Explorer, right-click the EarningsTracker.Services project, and select Add and then New Folder. Name the folder Settings.

Right-click the newly created Settings folder. From the context menu, select Add and then New Item…

In the Add New Item dialog box, select Interface under the Visual C# Items tab. Name it IIncome.cs, and click Add. Replace the generated code with the following:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

usingSystem;

namespaceEarningsTracker.Services.Settings

{

publicinterfaceIIncome

{

intId{get;set;}

stringName{get;set;}

decimalRevenue2013{get;set;}

decimalProfit2013{get;set;}

decimalRevenue2014{get;set;}

decimalProfit2014{get;set;}

decimalRevenue2015{get;set;}

decimalProfit2015{get;set;}

decimalRevenue2016{get;set;}

decimalProfit2016{get;set;}

decimalRevenue2017{get;set;}

decimalProfit2017{get;set;}

}

}

Next, add the Income class that implements IIncome interface:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

usingSystem;

usingSystem.ComponentModel.DataAnnotations;

namespaceEarningsTracker.Services.Settings

{

publicclassIncome:IIncome

{

[Key]

publicintId{get;set;}

[Required]

[Display(Name="Name")]

publicstringName{get;set;}

[Required]

[Display(Name="Revenue for 2013")]

publicdecimalRevenue2013{get;set;}

[Required]

[Display(Name="Profit for 2013")]

publicdecimalProfit2013{get;set;}

[Required]

[Display(Name="Revenue for 2014")]

publicdecimalRevenue2014{get;set;}

[Required]

[Display(Name="Profit for 2014")]

publicdecimalProfit2014{get;set;}

[Required]

[Display(Name="Revenue for 2015")]

publicdecimalRevenue2015{get;set;}

[Required]

[Display(Name="Profit for 2015")]

publicdecimalProfit2015{get;set;}

[Required]

[Display(Name="Revenue for 2016")]

publicdecimalRevenue2016{get;set;}

[Required]

[Display(Name="Profit for 2016")]

publicdecimalProfit2016{get;set;}

[Required]

[Display(Name="Revenue for 2017")]

publicdecimalRevenue2017{get;set;}

[Required]

[Display(Name="Profit for 2017")]

publicdecimalProfit2017{get;set;}

}

}

Rebuild the solution.

Task 3. Create data services in the EarningsTracker.Services project

Next, we will create two data services, i.e. DashboardService and SettingService. Both services contain logic to map the returned result from database to their respective data model. The SettingService updates income information for a specific office. We also inject the IRespository interface into the data services.

Add the IDashboardService interface to the Dashboards folder. Replace the generated code with the following:

The connection string is for a SQL Server database using SQL Server security. Replace the User ID and Password in DBConnection with the user credential to log on to your SQL server.

Rebuild the solution.

Task 8. Host and Test the ASP.NET Core Web APIs with IIS Express

In Solution Explorer, right-click the EarningsTracker.Api project, and select Properties.

In the EarningsTracker.Api pane, select Debug tab. Make sure IIS Express is selected and set the App URL to http://localhost:27368. To save file change, press Ctrl + S.

To launch the application in IIS Express, press F5. A default HTTP Get request of http://localhost:27368/api/values will be issued. A successful response will be returned as listed below:

To test the GetDashboardSetting method in the DashboardsController, we issue an HTTP Get request to http://localhost:27368/api/dashboards. A successful response will be returned as listed below:

To test the GetIncomeByOfficeId method in the SettingsController, we issue the following HTTP Get requests to:

http://localhost:27368/api/settings/1. A successful response for the Dallas office will be returned as listed below:

http://localhost:27368/api/settings/2. A successful response for the Seattle office will be returned as listed below:

http://localhost:27368/api/settings/3. A successful response for the Boston office will be returned as listed below:

Task 9. Publish the ASP.NET Core Web API to IIS

In Solution Explorer, right-click the EarningsTracker.Api project, and select Publish….

In the Publish dialog box, select the Custom option under the Profile tab.

In the New Custom Profile dialog box, set the Profile name to Local. Click OK to continue.

Under the Connection tab, select the File System as the Publish method. Set the Target location to C:\_tutorials\EarningsTrackerCoreRS\dist. Click Next to continue.

Under the Connection tab, make sure the following options are selected before clicking Next to continue:

Configuration: Release

Target Framework: .NETCoreApp,Version=v1.0

Target Runtime: Any

File Publish Options: Delete all existing files prior to publish

In the Publish dialog box, make sure Local is selected. Click Publish to continue.

Task 10. Add ASP.NET Core Web API to IIS

Open the IIS Manager. In the Connections pane, right-click the Application Pools, and select Add Application Pool….

In the Add Application Pool dialog box, name it ASP.NET Core App Pool. Select the No Managed Code option for the .NET CLR version and the Integrated option for the Managed pipeline mode. Check the box for Start application pool immediately. Click OK to continue.

Open the IIS Manager. In the Connections pane, expand the Sites node folder. Right-click the Default Web Site, and select Add Application….

In the Add Application dialog box, set the Alias to employee-tracker-core-apis. Select ASP.NET Core App Pool as the Application pool. In the Physical path text box, type C:\_tutorials\EmployeeTrackerCoreRS\dist. Click OK.

Task 11. Test the Web APIs with Postman

Let’s fire up Postman to test our Web APIs.

To test the GetDashboardSetting method in the DashboardsController, we issue an HTTP Get request to http://localhost/earnings-tracker-core-apis/api/dashboards. A successful response with 200 status code will be returned as listed below:

To test the GetIncomeByOfficeId method in the SettingsController, we issue the following HTTP Get requests to:

http://localhost/earnings-tracker-core-apis/api/settings/1. A successful response for the Dallas office will be returned as listed below:

http://localhost/earnings-tracker-core-apis/api/settings/2. A successful response for the Seattle office will be returned as listed below:

http://localhost/earnings-tracker-core-apis/api/settings/3. A successful response for the Boston office will be returned as listed below:

To test the UpdateIncomeByOfficeId method in the SettingsController, we will change the value of revenue2013 to 1700 for the Boston office. Let’s perform the following steps:

We issue an HTTP PUT request to http://localhost/earnings-tracker-core-apis/api/settings/3. We also enter the json data to the Request’s Body tab. In the Response’s Body, 5 indicates that SQL Server updated 5 records. A successful response with 200 status code will be returned as listed below:

We issue an HTTP GET request to http://localhost/earnings-tracker-core-apis/api/settings/3 to verify what we had just updated. A successful response for will be returned as listed below:

In the next tutorial series, we will create the Single-Page Application (SPA) interface using Angular and TypeScript.

Download Development Tool for Windows:

Task 1. Create the initial solution and projects

Click on Visual Studio 2015 to launch Visual Studio Community 2015. Then, select New Project from the Start page. Or, from the File menu, select New and then Project… to start a new solution.

In the New Project dialog box, select ASP.NET Core Web Application (.NET Core) under the Visual C# tab. Make sure .NET Framework 4.6.1 is selected, name it EarningsTracker.Api, set the Solution name to EarningsTrackerCoreRS, choose a Location and click OK.

The EarningsTracker.Api contains controllers for the Web API Restful interfaces.

In the New ASP.NET Core Web Application (.NET Core) dialog box, select the Web API under the ASP.NET Core Templates. Make sure that the Authentication option is set to No Authentication. Click OK to continue.

In Solution Explorer, right-click the EarningsTrackerCoreRS Solution, and select Add and then New Project…

In the Add New Project dialog box, select Class Library (.NET Core) under the Visual C# tab. Make sure .NET Framework 4.6.1 is selected, name it EarningsTracker.Services, and click OK.

The EarningsTracker.Services encapsulates the data access layer, and contains logic for retrieving data and mapping it to data models.

In the EarningsTracker.Service project, right-click the Class1.cs file and select Delete to remove the file.

In Solution Explorer, right-click the EarningsTrackerRS solution, and select Properties.

In Solution ‘EarningsTrackerCoreRS’ Property Pages dialog box, select Startup Project under the Common Properties tab. Make sure Single startup project is selected for EarningsTracker.Api.

In the same Solution ‘EarningsTrackerCoreRS’ Property Pages dialog box, select Project Dependencies under the Common Properties tab. Set the Projects to EarningsTracker.Api. Select the checkbox for EarningsTracker.Services under the Depends on: and click OK.

Task 2. Install the needed NuGet Packages to each project

From the Tools menu, select NuGet Package Manager and then Package Manager Console to launch the console.

In the Package Manager Console, select src\EarningsTracker.Api as the Default project. Select the nugget.org as the Package source.

JavaScript

1

2

Install-PackageAutofac.Extensions.DependencyInjection

Install-PackageMicrosoft.AspNetCore.Cors

Enter the above Install-Package command in line 1 and hit the enter key. Repeat this step till you have finished installing all two packages.

In the Package Manager Console, select src\EarningsTracker.Services as the Default project. Select the nugget.org as the Package source.

JavaScript

1

Install-PackageDapper

Enter the above Install-Package command in line 1 and hit the enter key.

I came across this article written by Joe Sauve on how to use Dapper accessing data from the database asynchronously. Dapper also supports numerous different database vendors. With that in mind, you can refactor the following classes to support different databases other than SQL Server.

In Solution Explorer, right-click the EarningsTracker.Services project, and select Add and then New Folder. Name the folder Common.

Right-click the newly created Common folder. From the context menu, select Add and then New Item…

In the Add New Item dialog box, select Interface under the Code tab. Name it IConnection.cs, and click Add.

Replace the generated code with the following:

C#

1

2

3

4

5

6

7

namespaceEarningsTracker.Services.Common

{

publicinterfaceIConnection

{

stringConnectionString{get;}

}

}

Once again, right-click the Common folder. From the context menu, select Add and then New Item…. In the Add New Item dialog box, select Class under the Code tab. Name it Connection.cs, and click Add.

Replace the generated code by adding the Connection class that implements IConnection interface:

NOTE: If you run into a compilation error related to Can not find runtime target for framework, please refer to the fix in here. Or compare your project.json file in the EarningsTracker.Api project with the one on Github.

Task 4. Register all services in the EarningsTracker.Api project

Next, we are going to use Autofac as the IoC container that will handle all the lifetime management of our dependencies and do the dependency injection for us.

The idea behind inversion of control is that, rather than tie the classes in your application together and let classes “new up” their dependencies, you switch it around so dependencies are instead passed in during class construction.Autofac

Following the ASP.NET Core Integration documentation on how to integrate Autofac into our application, we need to create a ContainerBuilder and then register our classes to expose their interfaces with it.

In the EarningsTracker.Api project, open the Startup.cs file. Replace the generated code with the following:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

usingSystem;

usingMicrosoft.AspNetCore.Builder;

usingMicrosoft.AspNetCore.Hosting;

usingMicrosoft.Extensions.Configuration;

usingMicrosoft.Extensions.DependencyInjection;

usingMicrosoft.Extensions.Logging;

usingAutofac;

usingAutofac.Extensions.DependencyInjection;

namespaceEarningsTracker.Api

{

publicclassStartup

{

publicStartup(IHostingEnvironment env)

{

varbuilder=newConfigurationBuilder()

.SetBasePath(env.ContentRootPath)

.AddJsonFile("appsettings.json",optional:true,reloadOnChange:true)

.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true)

.AddEnvironmentVariables();

Configuration=builder.Build();

}

publicIContainerApplicationContainer{get;privateset;}

publicIConfigurationRootConfiguration{get;}

// This method gets called by the runtime after the Startup constructor. Use this method to add services to the container.

Part 2: Create Web API Services

In the previous tutorial, we created the initial structure of the Employee Tracker Web API application in ASP.NET Core. In this tutorial, we will build the Web API services in Visual Studio Community 2015 Edition.

The Employee data model (class and interface) contains information of an employee.

In Solution Explorer, right-click the EmployeeTracker.Services project, and select Add and then New Folder. Name the folder Employees.

Right-click the newly created Employees folder. From the context menu, select Add and then New Item…

In the Add New Item dialog box, select Interface under the Visual C# Items tab. Name it IEmployee.cs, and click Add. Replace the generated code with the following:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

usingSystem;

namespaceEmployeeTracker.Services.Employees

{

publicinterfaceIEmployee

{

intId{get;set;}

stringFirstName{get;set;}

stringLastName{get;set;}

stringPosition{get;set;}

stringOffice{get;set;}

charSex{get;set;}

intAge{get;set;}

DateTimeStartDate{get;set;}

decimalSalary{get;set;}

}

}

Next, add the Employee class that implements IEmployee interface:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

usingSystem;

namespaceEmployeeTracker.Services.Employees

{

publicclassEmployee:IEmployee

{

publicintId{get;set;}

publicstringFirstName{get;set;}

publicstringLastName{get;set;}

publicstringPosition{get;set;}

publicstringOffice{get;set;}

publiccharSex{get;set;}

publicintAge{get;set;}

publicDateTimeStartDate{get;set;}

publicdecimalSalary{get;set;}

}

}

Rebuild the solution.

Task 3. Create data services in the EmployeeTracker.Services project

Next, we will create two data services, i.e. DashboardService and EmployeeService. Both services contain logic to map the returned result from database to their respective data model. We also inject the IRespository interface into the data services.

Add the IDashboardService interface to the Dashboards folder. Replace the generated code with the following:

The connection string is for a SQL Server database using SQL Server security. Replace the User ID and Password in DBConnection with the user credential to log on to your SQL server.

Rebuild the solution.

Task 8. Host and Test the ASP.NET Core Web APIs with IIS Express

In Solution Explorer, right-click the EmployeeTracker.Api project, and select Properties.

In the EmployeeTracker.Api pane, select Debug tab. Make sure IIS Express is selected and set the App URL to http://localhost:3009. To save file change, press Ctrl + S.

To launch the application in IIS Express, press F5. A default HTTP Get request of http://localhost:3009/api/values will be issued. A successful response will be returned as listed below:

To test the GetDashboardSetting method in the DashboardsController, we issue an HTTP Get request to http://localhost:3009/api/dashboards. A successful response will be returned as listed below:

To test the GetEmployees method in the EmployeesController, we issue an HTTP Get request to http://localhost:3009/api/employees. A successful response will be returned as listed below:

Task 9. Publish the ASP.NET Core Web API to IIS

In Solution Explorer, right-click the EmployeeTracker.Api project, and select Publish….

In the Publish dialog box, select the Custom option under the Profile tab.

In the New Custom Profile dialog box, set the Profile name to Local. Click OK to continue.

Under the Connection tab, select the File System as the Publish method. Set the Target location to C:\_tutorials\EmployeeTrackerCoreRS\dist. Click Next to continue.

Under the Connection tab, make sure the following options are selected before clicking Next to continue:

Configuration: Release

Target Framework: .NETCoreApp,Version=v1.0

Target Runtime: Any

File Publish Options: Delete all existing files prior to publish

In the Publish dialog box, make sure Local is selected. Click Publish to continue.

Task 10. Add ASP.NET Core Web API to IIS

Open the IIS Manager. In the Connections pane, right-click the Application Pools, and select Add Application Pool….

In the Add Application Pool dialog box, name it ASP.NET Core App Pool. Select the No Managed Code option for the .NET CLR version and the Integrated option for the Managed pipeline mode. Check the box for Start application pool immediately. Click OK to continue.

Open the IIS Manager. In the Connections pane, expand the Sites node folder. Right-click the Default Web Site, and select Add Application….

In the Add Application dialog box, set the Alias to employee-tracker-core-apis. Select ASP.NET Core App Pool as the Application pool. In the Physical path text box, type C:\_tutorials\EmployeeTrackerCoreRS\dist. Click OK.

Task 11. Test the Web APIs with Postman

Let’s fire up Postman to test our Web APIs.

To test the GetDashboardSetting method in the DashboardsController, we issue an HTTP Get request to http://localhost/employee-tracker-core-apis/api/dashboards. A successful response with 200 status code will be returned as listed below:

To test the GetEmployees method in the EmployeesController, we issue an HTTP Get request to http://localhost/employee-tracker-core-apis/api/employees. A successful response with 200 status code will be returned as listed below:

Task 12. Test the Web APIs with the clients

If you haven’t built one of the following clients in previous tutorials, let’s build one of the them:

Download Development Tool for Windows:

Task 1. Create the initial solution and projects

Click on Visual Studio 2015 to launch Visual Studio Community 2015. Then, select New Project from the Start page. Or, from the File menu, select New and then Project… to start a new solution.

In the New Project dialog box, select ASP.NET Core Web Application (.NET Core) under the Visual C# tab. Make sure .NET Framework 4.6.1 is selected, name it EmployeeTracker.Api, set the Solution name to EmployeeTrackerCoreRS, choose a Location and click OK.

The EmployeeTracker.Api contains controllers for the Web API Restful interfaces.

In the New ASP.NET Core Web Application (.NET Core) dialog box, select the Web API under the ASP.NET Core Templates. Make sure that the Authentication option is set to No Authentication. Click OK to continue.

In Solution Explorer, right-click the EmployeeTrackerCoreRS Solution, and select Add and then New Project…

In the Add New Project dialog box, select Class Library (.NET Core) under the Visual C# tab. Make sure .NET Framework 4.6.1 is selected, name it EmployeeTracker.Services, and click OK.

The EmployeeTracker.Services encapsulates the data access layer, and contains logic for retrieving data and mapping it to data models.

In the EmployeeTracker.Service project, right-click the Class1.cs file and select Delete to remove the file.

In Solution Explorer, right-click the EmployeeTrackerRS solution, and select Properties.

In Solution ‘EmployeeTrackerCoreRS’ Property Pages dialog box, select Startup Project under the Common Properties tab. Make sure Single startup project is selected for EmployeeTracker.Api.

In the same Solution ‘EmployeeTrackerCoreRS’ Property Pages dialog box, select Project Dependencies under the Common Properties tab. Set the Projects to EmployeeTracker.Api. Select the checkbox for EmployeeTracker.Services under the Depends on: and click OK.

Task 2. Install the needed NuGet Packages to each project

From the Tools menu, select NuGet Package Manager and then Package Manager Console to launch the console.

In the Package Manager Console, select src\EmployeeTracker.Api as the Default project. Select the nugget.org as the Package source.

JavaScript

1

2

Install-PackageAutofac.Extensions.DependencyInjection

Install-PackageMicrosoft.AspNetCore.Cors

Enter the above Install-Package command in line 1 and hit the enter key. Repeat this step till you have finished installing all two packages.

In the Package Manager Console, select src\EmployeeTracker.Services as the Default project. Select the nugget.org as the Package source.

JavaScript

1

Install-PackageDapper

Enter the above Install-Package command in line 1 and hit the enter key.

I came across this article written by Joe Sauve on how to use Dapper accessing data from the database asynchronously. Dapper also supports numerous different database vendors. With that in mind, you can refactor the following classes to support different databases other than SQL Server.

In Solution Explorer, right-click the EmployeeTracker.Services project, and select Add and then New Folder. Name the folder Common.

Right-click the newly created Common folder. From the context menu, select Add and then New Item…

In the Add New Item dialog box, select Interface under the Code tab. Name it IConnection.cs, and click Add.

Replace the generated code with the following:

C#

1

2

3

4

5

6

7

namespaceEmployeeTracker.Services.Common

{

publicinterfaceIConnection

{

stringConnectionString{get;}

}

}

Once again, right-click the Common folder. From the context menu, select Add and then New Item…. In the Add New Item dialog box, select Class under the Code tab. Name it Connection.cs, and click Add.

Replace the generated code by adding the Connection class that implements IConnection interface:

NOTE: If you run into a compilation error related to Can not find runtime target for framework, please refer to the fix in here. Or compare your project.json file in the EmployeeTracker.Api project with the one on Github.

Task 4. Register all services in the EmployeeTracker.Api project

Next, we are going to use Autofac as the IoC container that will handle all the lifetime management of our dependencies and do the dependency injection for us.

The idea behind inversion of control is that, rather than tie the classes in your application together and let classes “new up” their dependencies, you switch it around so dependencies are instead passed in during class construction.Autofac

Following the ASP.NET Core Integration documentation on how to integrate Autofac into our application, we need to create a ContainerBuilder and then register our classes to expose their interfaces with it.

In the EmployeeTracker.Api project, open the Startup.cs file. Replace the generated code with the following:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Threading.Tasks;

usingMicrosoft.AspNetCore.Builder;

usingMicrosoft.AspNetCore.Hosting;

usingMicrosoft.Extensions.Configuration;

usingMicrosoft.Extensions.DependencyInjection;

usingMicrosoft.Extensions.Logging;

usingAutofac;

usingAutofac.Extensions.DependencyInjection;

namespaceEmployeeTracker.Api

{

publicclassStartup

{

publicStartup(IHostingEnvironment env)

{

varbuilder=newConfigurationBuilder()

.SetBasePath(env.ContentRootPath)

.AddJsonFile("appsettings.json",optional:true,reloadOnChange:true)

.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true)

.AddEnvironmentVariables();

Configuration=builder.Build();

}

publicIContainerApplicationContainer{get;privateset;}

publicIConfigurationRootConfiguration{get;privateset;}

// This method gets called by the runtime after the Startup constructor. Use this method to add services to the container.