RESTHost - Before and After operation events
The RESTHost service has optional events that will execute before and after each operation. This allows you to override any details of the requests or responses, it also allows you to add generic functionality that will execute for each request and response.
In order to expose these events in the Designer, navigate to the Show events area of the RESTHost service Properties and select the checkboxes next to Before operation and After operation. The RESTHost service in the Solution Explorer should now have the following events visible:
The OperationEvents_BeforeOperation event will execute after the initial security validations and authentication event has succeeded.
In this event, the HTTPContext is available as an input.
You are then able to use these details to implement custom logic like the examples below:
Logging Request Attempts
Request attempts and their associated metadata could be logged before each operation, this can be done in a number of ways including logging attempts to a database or files.
In the below example the TextFileWrite function is used to log requests and their associated IP information to a local file.
Override Authenticate Event
You are also able to alter the HTTPContext of the output data of OperationEvents_Authenticate event. This allows you to override StatusCode, User etc. values.
In order to correctly alter the outgoing HTTPContext, you first need to initiate the entire $.Output.Data by assigning its value to $.Input.Data using the SetValue function:
Then you are able to assign specific values, in the example below, the User.IsAuthenticated value is overridden to False which means the result of OperationEvents_Authenticate event will be overridden to False and a 401 response will be returned and the request flow will cease.
Additional logic could be added to OperationEvents_BeforeOperation event which validates if the incoming request originates from a “whitelist” of IP addresses. If the IP is allowed then the flow can proceed, if the IP is invalid then a (401) Unauthorized response could be returned by overriding the $.Output.Data.User.IsAuthenticated of the OperationEvents_BeforeOperation event to False.
Return Status Code
If you alter the $.Output.Data.StatusCode to anything, including 200, the response will be returned from the OperationEvents_BeforeOperation event and the request flow will cease:
The OperationEvents_AfterOperation event event will execute after the operation has executed.
You are able to overwrite or append the HTTPContext from the operation.
Other guides for hosting a REST API
Sample solution: CRUD and file operations
View our sample solution on GitHub.