(C# ASP.NET Core) Using a static class for Route Handlers in a Minimal WebApi

So far, we have been writing all our minimal web api in the program.cs file. But this can become un-manageable and un-readable in a full blown project. We need a scheme for organizing our web api so that they can stay in a class of their own, inside a file of their own. We can even have a possibility of multiple classes - with each class containing all the related web api - those of a doctor in one file, whereas those of a patient in another. In this tutorial we have a brief look at the various possibilities, and finally I show an implementation of the scheme that I personally prefer.

Categories | About |     |  

Parveen,

Survey of the various strategies

There are various possibilities of specifying route handlers for a web api.

One is to have an inline lambda. It works very well for smaller projects, and is even better for cases where the handler is of one or two quick lines as you are seeing here.

app.MapGet("/doctor/all", () => { . . . });

Another possibility is to use a local function as you are seeing here. In this code we have a local function called handler. This function is then used in the MapGet api. This approach could work fine for a medium sized project.


var handler = () => {. . .};

app.MapGet("/doctor/all", handler);

Third possibility is to use an instance method of a separately written class. For example we can add a suitable class to our project, such as MyHandler, and add suitable instance functions to this class.


class MyHandler
{
    // code for the web api 
    public void fx()
    {
        . . . 
    }
}

The function fx contains the code for our handler. This instance function can now be wired to the web api as shown here.


MyHandler h = new MyHandler();

app.MapGet("/doctor/all", h.fx);

As you must have noticed that we need to first create an instance of the class, and then call the specific function from there. This step can be done away with by using a static class instead, and that will make it more neat.

Video Explanation (see it happen!)

Please watch the following youtube video:

Using a static class for organizing our web api

The approach I prefer is to use a static class. And, now I shall demonstrate how we can modify our existing web api project so that it uses a static class for neatly holding all our web api.

Our project has about six web api - and now it's time to put all of them in a static class.

Open the web api project, and right click it to add a folder called, say, WebApiHandlers. This folder can contain all our static classes for the route handlers. Right click this folder and add a class called, say, DoctorWebApiMapper. Double click and open this file so that we can examine the code.

This is the file DoctorWebApiMapper.cs, and it contains a static class called DoctorWebApiMapper.

We have added a function called ConfigureWebApi to register all our six or seven web api. Let us have a look at the first of them.


public static class DoctorWebApiMapper
{
    public static void ConfigureWebApi(WebApplication app)
    {
        app.MapGet("/doctor/all", GetAll);
        app.MapGet("/doctor/fees/{amt:int:min(0)}", GetMinFees);
        app.MapGet("/doctor/{id}", GetDoctorById);

        app.MapPost("/doctor", PostDoctor);
        app.MapPut("/doctor/{id}", PutDoctor);
        app.MapDelete("/doctor/{id}", DeleteDoctor);
    }

    private static async Task<List<DoctorDTO>> GetAll(MyApiContext ctx)
    {
        return await ctx.Doctors.Select(x => new DoctorDTO(x)).ToListAsync();
    }

        // . . . more functions  
        // the project can be downloaded from the  
        // attachments of this video 
}

The route handler is a separate static function of this class. The code for the api is now contained in this function. As you can see, this is more readable, and neat. This class can grow as per the needs, and yet remain readable.

We have ported all the web api of our project to this class - and you can obtain the project from the downloads attached to this video.

Let us also have a look at the program.cs file now!

As you can see, there is a single call to the ConfigureWebApi function, and that we have removed all the six web api from this file - making it more neat!


// program.cs 

// . . . code above not shown, being irrelevant here 

// map the web api, single line now! 
DoctorWebApiMapper.ConfigureWebApi(app);

app.MapRazorPages();

app.Run();

Verify the Project

Now we can run the project to verify that it serves a Get web api successfully. We can similarly, verify that other api are also working fine - thanks!


This Blog Post/Article "(C# ASP.NET Core) Using a static class for Route Handlers in a Minimal WebApi" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.