How to write efficient controllers in ASP.Net Core


You can write better controllers by adhering to the best practices. So-called “thin” controllers—i.e. controllers with less code and fewer responsibilities—are easier to read and maintain. And once your controllers are thin, you might not need to test them much. Rather, you can focus on testing the business logic and data access code. Another advantage of a thin or lean controller is that it is easier to maintain multiple versions of the controller over time.

This article discusses bad habits that make controllers fat and then explores ways to make the controllers lean and manageable. My list of best practices in writing controllers may not be comprehensive, but I have discussed the most important ones with relevant source code wherever applicable. In the sections that follow, we’ll examine what a fat controller is, why it is a code smell, what a thin controller is, why it is beneficial, and how to make the controllers thin, simple, testable, and manageable. 

Remove data access code from controllers

When writing a controller, you should adhere to the , meaning the controller should have “one responsibility” or “one and only one reason to change.” In other words, you want to keep the reasons for changing the controller code to a minimum. Consider the following piece of code that shows a typical controller with data access logic.

public class AuthorController : Controller
    private AuthorContext dataContext = new AuthorContext();
    public ActionResult Index(int authorId)
        var authors = dataContext.Authors
            .Where(x=>x.AuthorId == authorId)
        return View(authors);
    //Other action methods