Tutorials / Build a REST API with C# and .NET · Lesson 31 of 45

Backend

On this page

    Where Business Rules Live

    The books service said that a nightly job could use the same service as the API, and get the same rules. Let's check that. Every night, the bookshop's supplier sends a file with new books. A small program, a batch job (a program that runs by itself, with nobody watching), reads the file and adds the books to the shop through the book service. One night the file has a book with a price of -1. Nothing complains, and the shop now has a book with a negative price.

    Our goal: refuse a bad book whoever saves it, and not only when it comes through the API.

    Here is the route:

    1. Send a bad book through the service, as the batch job would, and see it get saved.
    2. Move the check into the service.
    3. Fix the tests that the new check breaks.
    4. See where each kind of rule lives.

    This lesson shows only the lines that change, so the idea stays in view. It leaves out rules that need other data (such as "no two books with the same title"), turning the service's error into a 400 for the API, and what the database can enforce by itself (a required column, a link between two tables).


    Two callers

    Two programs can save a book, and they take different routes:

    Two callers of the book service The API Batch job Request rules Book service Books table no request rules here
    • The API checks every request against its rules first. That is the work of the last two lessons.
    • The batch job is a different program. It calls the book service directly, so it never meets the request's rules. They belong to the API.

    Book already carries [Required] and [Range], but an attribute is only a label. Something has to read it and act. In the API, ASP.NET does. In the batch job, nothing does, and the service does not either. So today only the API has a guard.

    To see it, add a test to BookServiceTests in tests/BookShop.Data.Tests/. It saves a book with a price of -1 through the service, as the batch job would, and expects the service to refuse it:

    [TestMethod]
    public async Task CreateAsync_NegativePrice_IsRefused()
    {
        var book = new Book { Title = "Clean Code", Author = "Robert C. Martin", Price = -1m, Stock = 7, Category = "Programming" };
    
        await Assert.ThrowsExactlyAsync<ValidationException>(() => _service.CreateAsync(book));
    }
    

    (It needs using System.ComponentModel.DataAnnotations; at the top of the file.) Run dotnet test. The test fails, and the message says it plainly:

    Assert.ThrowsExactlyAsync failed. Expected exception type:<System.ComponentModel.DataAnnotations.ValidationException> but no exception was thrown.
    

    The book with the price of -1 was saved. That is the gap.


    The service checks the book

    The service is the one class that every program using our data code goes through, so it is the right place for a check that must hold for all of them. It already knows what a good book looks like: the attributes on Book. It only has to read them. In BookService, one line goes at the top of CreateAsync, and the same line at the top of UpdateAsync:

    public async Task<Book> CreateAsync(Book book)
    {
        Validator.ValidateObject(book, new ValidationContext(book), validateAllProperties: true);   // new
        _context.Books.Add(book);
        await _context.SaveChangesAsync();
        return book;
    }
    

    (The file needs using System.ComponentModel.DataAnnotations; too.)

    • Validator.ValidateObject reads the attributes on the book and checks every property against them. It is the checker that ASP.NET uses for requests, so the rules are the same ones.
    • When a rule fails, it throws a ValidationException, and the save never happens. The message names the rule, for example The field Price must be between 0.01 and 10000.

    The new test passes. The book with the price of -1 is refused.

    Why an exception, when business rules and meaningful errors used a result for "not enough copies"? Not enough copies is an ordinary outcome that happens every week. A book that breaks its own rules means the caller made a mistake, and the service cannot do its job. That is what an exception is for.

    The API still keeps its own check on the request. It answers first, and it gives a person using the API a friendly 400 that lists every problem. The service's check is for everyone else, so our own API will not normally meet this exception. If one ever did get through, the exception handler from errors, the professional way would answer with a 500, which is the right answer for "our own code sent a bad book".


    The old tests break

    Run the whole suite again. Four older service tests now fail:

    Failed CreateAsync_ValidBook_SavesItAndGivesItAnId
      ValidationException: The Category field is required.
    Failed CreateAsync_TwoBooks_GetDifferentIds
      ValidationException: The Author field is required.
    Failed UpdateAsync_BodyHasAnotherId_KeepsTheIdOfTheAddress
      ValidationException: The Author field is required.
    Failed UpdateAsync_UnknownId_ReturnsFalse
      ValidationException: The Author field is required.
    

    (Shortened: the real output shows the name and the message of each failure, and more.) A new rule can show how sloppy the test data was. These tests saved a book with only a title, or without a category. Those books were never complete, and nothing noticed until a check came along. The fix is in the tests, not in the rule: give them a full book. A small helper in BookServiceTests builds one:

    private static Book ValidBook(string title)
    {
        return new Book { Title = title, Author = "Robert C. Martin", Price = 34.50m, Stock = 7, Category = "Programming" };
    }
    

    Each of the four tests uses it. One of them, as an example:

    [TestMethod]
    public async Task CreateAsync_TwoBooks_GetDifferentIds()
    {
        // var first = await _service.CreateAsync(new Book { Title = "Clean Code" });           // replaced
        // var second = await _service.CreateAsync(new Book { Title = "Refactoring" });         // replaced
        var first = await _service.CreateAsync(ValidBook("Clean Code"));                        // new
        var second = await _service.CreateAsync(ValidBook("Refactoring"));                      // new
    
        Assert.AreNotEqual(first.Id, second.Id);
    }
    

    (The commented lines show the old form and can be deleted. The other three change the same way. The test for another id in the body also sets replacement.Id = 99 after calling ValidBook.) Run dotnet test again, and everything passes.


    Where the rules live

    A rule about what a good book is, such as "a price is at least one cent", is a business rule. It belongs in the one place every program passes through: the service. Then a second program, a third tool or a future import gets the rule for free, and nobody has to copy it and keep the copies in step.

    Layer What it holds
    The API Turning a request into a call to the service, and the answer into a status code. Its request rules give people a quick, friendly 400.
    The service The business rules: what a good book is, and what a sale needs.
    The database The shape of the data: a required column, a link between two tables.

    The database does check some things, but only the shape. It cannot judge what a good price is, and it should not try: the rule would then live in two places, and one of them is much harder to change.


    Recap

    • The books service promised that another program, such as a nightly batch job, could reuse the service. That only helps if the rules are in the service.
    • An attribute such as [Range] is only a label until something reads it. ASP.NET reads it for requests. A batch job never goes through a request, so nothing read it.
    • The service checks every book it saves with Validator.ValidateObject, using the attributes already on Book. A bad book throws a ValidationException, and nothing is saved.
    • A bad book is the caller's mistake, so the service throws an exception. A normal outcome, like "not enough copies", is a result.
    • Adding a rule can break older tests that used half-filled books. Fix the data in the tests, not the rule.
    • The API keeps a check on the request for a quick, friendly 400. The service holds the business rules for every caller. The database keeps the shape of the data.

    Questions to think about

    Each question has its answer folded away underneath. Guess first, then open it to check.

    1. Why did a bad book get saved when a nightly batch job used the service?
    Show answer

    The rule only ran on requests that came through the API. The batch job called the service directly, and the service did not check the book.

    1. Where should a business rule, such as the lowest price, live?
    Show answer

    In the service, the one place every program passes through. Then every caller gets the rule, and nobody keeps a copy.

    1. If the service checks the book, why does the API still check the request?
    Show answer

    The API's check answers first, with a friendly 400 for the person who sent the request. The service's check is for every other caller.

    Next lesson: the first web page, which calls the books endpoint and shows the list.

    ← More Validation RulesMaking a Page Change →