In this article by Shahed Chowdhuri author of book ASP.Net Core Essentials, we will work through a working sample of a web API project. During this lesson, we will cover the following:
(For more resources related to this topic, see here.)
Building web applications can be a rewarding experience. The satisfaction of reaching a broad set of potential users can trump the frustrating nights spent fine-tuning an application and fixing bugs. But some mobile users demand a more streamlined experience that only a native mobile app can provide.
Mobile browsers may experience performance issues in low-bandwidth situations, where HTML5 applications can only go so far with a heavy server-side back-end. Enter web API, with its RESTful endpoints, built with mobile-friendly server-side code.
In order to create a piece of software, years of wisdom tell us that we should build software with users in mind. Without use cases, its features are literally useless. By designing features around user stories, it makes sense to reveal public endpoints that relate directly to user actions. As a result, you will end up with a leaner web application that works for more users.
If you need more convincing, here's a recap of features and benefits:
Let's build a sample web application named Patient Records. In this application, we will create a web API from scratch to allow the following tasks:
These four actions make up the so-called CRUD operations of our system: to Create, Read, Update or Delete patient records.
Following the steps below, we will create a new project in Visual Studio 2015:
The preceding steps have been expanded into detailed instructions with the following screenshots:
In Visual Studio 2015, click File | New | Project. You can also press Ctrl+Shift+N on your keyboard.
On the left panel, locate the Web node below Visual C#, then select ASP.NET Core Web Application (.NET Core), as shown in the following screenshot:
With this project template selected, type in a name for your project, for examplePatientRecordsApi, and choose a location on your computer, as shown in the following screenshot:
Optionally, you may select the checkboxes on the lower right to create a directory for your solution file and/or add your new project to source control. Click OK to proceed.
In the dialog that follows, select Empty from the list of the ASP.NET Core Templates, then click OK, as shown in the following screenshot:
Optionally, you can check the checkbox for Microsoft Azure to host your project in the cloud. Click OK to proceed.
In the Solution Explorer, you may observe that your References are being restored. This occurs every time you create a new project or add new references to your project that have to be restored through NuGet,as shown in the following screenshot:
Follow these steps, to fix your references, and build your Web API project:
Rightclickon your project, and click Add | New Folder to add a new folder, as shown in the following screenshot:
Perform the preceding step three times to create new folders for your Controllers, Models, and Views,as shown in the following screenshot:
Rightclick on your Controllers folder, then click Add | New Item to create a new API controller for patient records on your system, as shown in the following screenshot:
In the dialog box that appears, choose Web API Controller Class from the list of options under .NET Core, as shown in the following screenshot:
Name your new API controller, for examplePatientController.cs, then click Add to proceed.
In your new PatientController, you will most likely have several areas highlighted with red squiggly lines due to a lack of necessary dependencies, as shown in the following screenshot. As a result, you won't be able to build your project/solution at this time:
In the next section, we will learn about how to configure your web API so that it has the proper references and dependencies in its configuration files.
How does the web server know what to send to the browser when a specific URL is requested? The answer lies in the configuration of your web API project.
In this section, we will learn how to set up your dependencies automatically using the IDE, or manually by editing your project's configuration file.
To pull in the necessary dependencies, you may right-click on the using statement for Microsoft.AspNet.Mvc and select Quick Actions and Refactorings…. This can also be triggered by pressing Ctrl +. (period) on your keyboard or simply by hovering over the underlined term, as shown in the following screenshot:
Visual Studio should offer you several possible options, fromwhich you can select the one that adds the package Microsoft.AspNetCore.Mvc.Corefor the namespace Microsoft.AspNetCore.Mvc. For the Controller class, add a reference for the Microsoft.AspNetCore.Mvc.ViewFeaturespackage, as shown in the following screenshot:
Fig12: Adding the Microsoft.AspNetCore.Mvc.Core 1.0.0 package
If you select the latest version that's available, this should update your references and remove the red squiggly lines, as shown in the following screenshot:
Fig13:Updating your references and removing the red squiggly lines
The precedingstep should automatically update your project.json file with the correct dependencies for theMicrosoft.AspNetCore.Mvc.Core, and
Microsoft.AspNetCore.Mvc.ViewFeatures, as shown in the following screenshot:
The "frameworks" section of theproject.json file identifies the type and version of the .NET Framework that your web app is using, for examplenetcoreapp1.0 for the 1.0 version of .NET Core. You will see something similar in your project, as shown in the following screenshot:
Click the Build Solution button from the top menu/toolbar. Depending on how you have your shortcuts set up, you may press Ctrl+Shift+B or press F6 on your keyboard to build the solution. You should now be able to build your project/solution without errors, as shown in the following screenshot:
Before running the web API project, open the Startup.cs class file, and replace the app.Run() statement/block (along with its contents) with a call to app.UseMvc()in the Configure() method. To add the Mvc to the project, add a call to the services.AddMvcCore() in the ConfigureServices() method. To allow this code to compile, add a reference to Microsoft.AspNetCore.Mvc.
Let's take a closer look at the PatientController class. The auto-generated class has the following methods:
The Get() method simply returns a JSON object as an enumerable string of values, while the Get(int id) method is an overridden variant that gets a particular value for a specified ID.
The Post() and Put() methods can be used for creating and updating entities. Note that the Put() method takes in an ID value as the first parameter so that it knows which entity to update.
Finally, we have the Delete() method, which can be used to delete an entity using the specified ID.
You may run the web API project in a web browser that can display JSON data.
If you use Google Chrome, I would suggest using the JSONView Extension (or other similar extension) to properly display JSON data.
The aforementioned extension is also available on GitHub at the following URL:
https://github.com/gildas-lormeau/JSONView-for-Chrome
If you use Microsoft Edge, you can view the raw JSON data directly in the browser.Once your browser is ready, you can select your browser of choice from the top toolbar of Visual Studio. Click on the tiny triangle icon next to the Debug button, then select a browser, as shown in the following screenshot:
In the preceding screenshot, you can see that multiple installed browsers are available, including Firefox, Google Chrome, Internet Explorer,and Edge. To choose a different browser, simply click on Browse With…, in the menu to select a different one.
Now, click the Debug button (that isthe green play button) to see the web API project in action in your web browser, as shown in the following screenshot. If you don't have a web application set up, you won't be able to browse the site from the root URL:
Don’t worry if you see this error, you can update the URL to include a path to your API controller, for an example seehttp://localhost:12345/api/Patient.
Note that your port number may vary. Now, you should be able to see a list of views that are being spat out by your API controller, as shown in the following screenshot:
Back in the days of classic ASP, application URL paths typically reflected physical file paths. This continued with ASP.NET web forms, even though the concept of custom URL routing was introduced. With ASP.NET MVC, routes were designed to cater to functionality rather than physical paths.
ASP.NET web API continues this newer tradition, with the ability to set up custom routes from within your code. You can create routes for your application using fluent configuration in your startup code or with declarative attributes surrounded by square brackets.
To understand the purpose of having routes, let's focus on the features and benefits of routes in your application. This applies to both ASP.NET MVC and ASP.NET web API:
Let's start with this simple class-level attribute that specifies a route for your API controller, as follows:
[Route("api/[controller]")]
public class PatientController : Controller
{
// ...
}
Here, we can dissect the attribute (seen in square brackets, used to affect the class below it) and its parameter to understand what's going on:
For method calls, you can define a route with or without parameters. The following two examples illustrate both types of route definitions:
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
In this example, the Get() method performs an action related to the HTTP verb HttpGet, which is declared in the attribute directly above the method. This identifies the default method for accessing the controller through a browser without any parameters, which means that this API method can be accessed using the following syntax:
http://MyApplicationServer/api/Patient
To include parameters, we can use the following syntax:
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
Here, the HttpGet attribute is coupled with an "{id}" parameter, enclosed in curly braces within double quotes. The overridden version of the Get() method also includes an integer value named id to correspond with the expected parameter.
If no parameter is specified, the value of id is equal to default(int) which is zero. This can be called without any parameters with the following syntax:
http://MyApplicationServer/api/Patient/Get
In order to pass parameters, you can add any integer value right after the controller name, with the following syntax:
http://MyApplicationServer/api/Patient/1
This will assign the number 1 to the integer variable id.
To test the aforementioned routes, simply run the application from Visual Studio and access the specified URLs without parameters.
The preceding screenshot show the results of accessing the following path:
http://MyApplicationServer/api/Patient/1
If a web API exposes public endpoints, but there is no client application there to consume it, does it really exist? Without getting too philosophical, let's go over the possible ways you can consume a client application.
You can do any of the following:
If you don't have a client application set up, you can use an external tool such as Fiddler. Fiddler is a free tool that is now available from Telerik, available at http://www.telerik.com/download/fiddler, as shown in the following screenshot:
You can use Fiddler to inspect URLs that are being retrieved and submitted on your machine. You can also use it to trigger any URL, and change the request type (Get, Post, and others).
Since this article is primarily about the ASP.NET core web API, we won't go into detail about mobile application development. However, it's important to note that a web API can provide a backend for your mobile app projects.
Mobile apps may include Windows Mobile apps, iOS apps, Android apps, and any modern app that you can build for today's smartphones and tablets. You may consult the documentation for your particular platform of choice, to determine what is needed to call a RESTful API.
A web client, in this case, refers to any HTML/JavaScript application that has the ability to call a RESTful API. At the least, you can build a complete client-side solution with straight JavaScript to perform the necessary actions. For a better experience, you may use jQuery and also one of many popular JavaScript frameworks.
A web client can also be a part of a larger ASP.NET MVC application or a Single-Page Application (SPA). As long as your application is spitting out JavaScript that is contained in HTML pages, you can build a frontend that works with your backend web API.
In this article, we've taken a look at the basic structure of an ASP.NET web API project, and observed the unification of web API with MVC in an ASP.NET core. We also learned how to use a web API as our backend to provide support for various frontend applications.
Further resources on this subject: