RESTHost - Before and After operation events
Last updated
Last updated
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, and 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:
OperationEvents_AfterOperation
OperationEvents_BeforeOperation
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:
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.
You are also able to alter the HTTPContext of the output data of the 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 the OperationEvents_Authenticate event will be overridden to False
, and a 401 response will be returned, causing the request flow to cease.
Additional logic could be added to the 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
.
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 will execute after the operation has executed.
You are able to overwrite or append the HTTPContext from the operation.
View our sample solution on .