Book Image

Customizing ASP.NET Core 6.0 - Second Edition

By : Jürgen Gutsch
Book Image

Customizing ASP.NET Core 6.0 - Second Edition

By: Jürgen Gutsch

Overview of this book

ASP.NET Core is packed full of hidden features for building sophisticated web applications – but if you don’t know how to customize it, you’re not making the most of its capabilities. Customizing ASP.NET Core 6.0 is a book that will teach you all about tweaking the knobs at various layers and take experienced programmers’ skills to a new level. This updated second edition covers the latest features and changes in the .NET 6 LTS version, along with new insights and customization techniques for important topics such as authentication and authorization. You’ll also learn how to work with caches and change the default behavior of ASP.NET Core apps. This book will show you the essential concepts relating to tweaking the framework, such as configuration, dependency injection, routing, action filters, and more. As you progress, you'll be able to create custom solutions that meet the needs of your use case with ASP.NET Core. Later chapters will cover expert techniques and best practices for using the framework for your app development needs, from UI design to hosting. Finally, you'll focus on the new endpoint routing in ASP.NET Core to build custom endpoints and add third-party endpoints to your web apps for processing requests faster. By the end of this book, you'll be able to customize ASP.NET Core to develop better, more robust apps.
Table of Contents (18 chapters)

Using ActionFilter

Action filters that are actually attributes can be registered as an attribute of an Action or a Controller, as illustrated in the following code snippet:

[HttpPost]
[ValidateModel] // ActionFilter as attribute
public ActionResult<Person> Post([FromBody] Person model)
{
    // save the person
    return model; //just to test the action
}

Here, we use ValidateModel attribute that checks the ModelState and returns BadRequestObjectResult in case the ModelState is invalid; we don't need to check the ModelState in the actual Action.

To register action filters globally, you need to extend the MVC registration in the ConfigureServices method of the Startup.cs file, as follows:

builder.Services.AddControllersWithViews()
    .AddMvcOptions(options =>
    {
        options.Filters.Add(new SampleActionFilter());
   ...