How to Get Started with ASP.NET for API Development
ASP.NET is a platform for building web APIs with C# and .NET. It’s commonly used for app backends, and can automatically serialize classes to JSON. We’ll walk through setting up a service that talks to a database and stores a list of objects.
Creating a Project
We’ll be using Visual Studio, as it provides great .NET support out of the box. Create a new project using the “ASP.NET Core Web Application” template:
Give it a name, and select “API,” as we’re not building a ASP.NET frontend here.
This will initialize your solution with all the boilerplate needed to get a basic API up and running. If you click the run button (labelled IIS Express, which starts an IIS web server), you’ll see the API displaying some dummy data about the weather.
We’ll use this base to set up a simple API that will connect to a database and read and write custom objects. In this case, it’s a collection of user data, but the API will largely work the same for more complicated entity models.
Connecting a Database
It’s a good idea to split up the logic of handling requests and the logic of handling talking to the database. We’ll create a database service with some functions for reading and writing, then an a API controller that will respond to requests by talking to the database service. The first thing to do, though, is get ASP.NET talking to a database in the first place.
We’ll need to install some packages for working with a database. Click on Tools > NuGet Package Manager, and select “Manage NuGet Packages For Solution.”
If you’re using a SQL database, the database connection is handled with specific plugin packages that implement EntityFrameworkCore for the underlying database. This is a framework that maps C# objects to a relational database, and allows you to use LINQ queries and other native tools to interact with it. You can find a full list of database providers here for most popular relational databases.
We’ll be going with MongoDB here, because NoSQL document databases translate to a List
Comments are closed.