Creating a .Net Core REST API — Part 2: Controller setup

Kieran Gillibrand
4 min readJan 3, 2019

--

This is the 2nd part of a series of tutorials I’m putting together on creating a REST API with ASP.Net Core and Entity Framework Core. Last time we got our project setup and generated models from our database. This time we’ll setup our database connection for the API itself, the API controller, and implement a handler for HTTP GET requests.

Database Connection

For our API to query our database we need to store our connection string somewhere and make our BlogContext available in the API controller.

There are a few options for storing connection strings in ASP.Net Core but we will be storing it in appsettings.json. Note that this file should never be in source control when it contains data like this.

Following the format in the link above will give us an appsettings.json looking something like this.

While our connection string for modelling is usually fairly simple you can configure database specific parameters in the API connection string. These parameters may affect security (SSL modes) or performance.

After adding our connection string we need to tell ASP.Net that we’re using Postgres and which connection string should be used. Note that name of the connection string should match your appsettings.json.

We register the DataContext and its connection string in the ConfigureServices method of Startup.cs

After this we need to register our DataContext for dependency injection to our API controller.

AddScoped() registers our DataContext

API Controller

ValuesController is the default API controller that the project template generated for us. Currently it just returns some hardcoded values so we’ll make some adjustments.

  1. Firstly we should rename the controller class and source file. By convention the name of the controller (without the ‘Controller’ suffix) determines the endpoint of our API. I renamed it to PostsController as its operations are performed on blog posts.
  2. Because we registered our DataContext as a service it will be injected through the Controller constructor. We just need to accept it as a parameter and store it.
We add the single parameter constructor and store the provided DataContext.

GET Handler

Now we will implement a simple handler for HTTP GET requests to the Posts resource. We will start with GET as it’s a simple way of testing our database connection. Our GET handler will simply return the full representation of every post in the database, optionally filtering with an isPublic value.

Our handler is marked with the [HttpGet] which corresponds to its HTTP verb. It returns an ActionResult that contains some data. There are various provided implementations of ActionResult which correspond to HTTP status codes. HTTP 200 (OK) is represented by either OkResult (no content) or OkObjectResult (contains content). This convention is shared by the other results as well. If the result contains content then ASP.Net Core will automatically stringify it to JSON.

Our isPublic filter value is automatically parsed from the query string. Because query string parameters are generally optional it is a nullable bool which will be null if not provided. If you wish you can leave off the [FromQuery] attribute and the model binding rules will be followed to find the parameter.

If you’re not familiar with Entity Framework (Core or otherwise) it is generally queried using LINQ. Either with the query or method syntax. Behind the scenes EF Core and your database provider will generate an SQL query corresponding to queries against the DataContext collections (Posts, Comments, Users).

Reference Loop Handling

You may notice that our database schema and models have a potential for infinite loops in them. You can navigate from Post -> Author -> Posts -> Author … As you can imagine this presents a problem for JSON.Net. In my experience my JSON response was malformed and cut in half.

To resolve this issue you can instruct JSON.Net to ignore the loops:

Back in Startup.cs we can control various options of the JSON serialization

Testing the API

If you’ve added some data to your database manually then you can test the API with a tool like Postman.

Because we’ve renamed the controller our endpoint will now be located at api/posts instead of api/values. Visual Studio will still launch your web browser pointing at api/values but you can change that in Solution Explorer -> Properties -> launchSettings.json.

Next Time

Next time we’ll implement other handlers for create, update, and delete (POST, PUT, DELETE).

The code for this example is available on Github. Up next we’ll finish the other HTTP methods in our controller.

--

--