Book Image

ASP.NET Core MVC 2.0 Cookbook

By : Jason De Oliveira, Engin Polat, Stephane Belkheraz
Book Image

ASP.NET Core MVC 2.0 Cookbook

By: Jason De Oliveira, Engin Polat, Stephane Belkheraz

Overview of this book

The ASP.NET Core 2.0 Framework has been designed to meet all the needs of today’s web developers. It provides better control, support for test-driven development, and cleaner code. Moreover, it’s lightweight and allows you to run apps on Windows, OSX and Linux, making it the most popular web framework with modern day developers. This book takes a unique approach to web development, using real-world examples to guide you through problems with ASP.NET Core 2.0 web applications. It covers Visual Studio 2017- and ASP.NET Core 2.0-specifc changes and provides general MVC development recipes. It explores setting up .NET Core, Visual Studio 2017, Node.js modules, and NuGet. Next, it shows you how to work with Inversion of Control data pattern and caching. We explore everyday ASP.NET Core MVC 2.0 patterns and go beyond it into troubleshooting. Finally, we lead you through migrating, hosting, and deploying your code. By the end of the book, you’ll not only have explored every aspect of ASP.NET Core MVC 2.0, you’ll also have a reference you can keep coming back to whenever you need to get the job done.
Table of Contents (26 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Using a filter globally versus using a middleware


In this recipe, you will learn how to use a filter globally, and understand the difference between using a filter globally and using middleware.

Getting ready

Let's create an empty web application with VS 2017.

How to do it...

  1. First, let's create a ResultFilter class by deriving from IResultFilter:
public class MyResultFilter : IResultFilter
{
  public void OnResultExecuting(ActionExecutingContext context)
  {
    // do something before the action executes
  }
  public void OnResultExecuted(ActionExecutedContext context)
  {
    // do something after the action executes
    ViewResult result = context.Result as ViewResult;
    if (result != null)
    {
      result.ViewData["globalMessage"] =
      "Comes from MyActionAttributeFilter at " +
      DateTime.Now.ToLongTimeString();
    }
  }
}
  1. Next, let's configure this filter to be used as a global filter in Startup.cs. We can do this in two ways; by type, or by instance:
services.AddMVC(config =...