Interceptors
Interceptors allow you to process validation and business logic before and after Entities hit the database.For example, you may need to validate some external business rules before the object is saved, but then after it’s saved, you may need to dump the object to an Azure Storage Queue to get picked up by a WebJob for further processing out-of-band.
No matter what approach you choose, the concept is simple. Either technique uses a function that returns boolean:
- Return
true, and processing continues normally - Return
false, and RESTier returns a 403 Unauthorized to the client
Convention-Based Interception
Users can control if one of the four submit operations is allowed on some entity set or action by putting someprotected internal methods into the Api class. The method name must conform to the convention:
- BeforeOperation
- AfterOperation
- TargetName
The possible values for
{BeforeOperation} are:- Inserting
- Updating
- Deleting
- Executing
Example
The example below demonstrates how both types of{TargetName} can be used:
Method 1: OnInsertingTrip
Method 1: OnInsertingTrip
Shows validation before inserting - checks if the Trip Description is not blank
Method 2: OnInsertedTrip
Method 2: OnInsertedTrip
Shows processing after inserting - logs the operation and could trigger additional business processes
TrippinApi.cs
Centralized Interception
In addition to the more granular convention-based approach, you can also centralize processing into one location.Users can use interface
IChangeSetItemAuthorizer to define any customized authorize logic to see whether a user is authorized for the specified submit. If this method returns false, then the related query will get error code 403 (Forbidden).1
Create authorizer class
Create a class that implements
IChangeSetItemAuthorizer2
Register with DI
Register that class with RESTier through Dependency Injection (DI)
Example
CustomAuthorizer.cs
Unit Testing Considerations
Because both of these methods are de-coupled from the code that interacts with the database, the Authorization logic is easily testable, without having to fire up the entire Web API + RESTier pipeline.
Setting up your Unit Test
1
Create test project
If you don’t have a unit test project for your API project already, start by creating one. Repeat the process outlined in “Getting Started” to install the RESTier packages into your Unit Test project.
2
Add FluentAssertions
Add the FluentAssertions package to your test project:
3
Make internals visible
Go back to your API project. Expand the “Properties” node, double-click
AssemblyInfo.cs, and add the following line to the very end of the file:Example
Given the Convention-Based Authorization example, the tests below should have 100% code coverage, and should pass without any required changes.TrippinApiTests.cs