RESTHost Guide - Before and After operation events

RESTHost - Before and After operation events

RESTHost svc 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 svc Properties and select the checkboxes next to Before operation and After operation. The RESTHost svc in the Solution Explorer should now have the following events visible:

  • OperationEvents_AfterOperationEVT
  • OperationEvents_BeforeOperationEVT

Before Operation

The OperationEvents_BeforeOperationEVT 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 FNC is used to log requests and their associated IP information to a local file.

image


Override Authenticate Event

You are also able to alter the HTTPContext of the output data of OperationEvents_AuthenticateEVT. 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 SetValue FNC:

image78

image79

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_AuthenticateEVT will be overridden to False and a 401 response will be returned and the request flow will cease.

image81


IP Whitelisting

Additional logic could be added to OperationEvents_BeforeOperation EVT 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 OperationEvents_BeforeOperation EVT to False.

image


Return Status Code

If you alter the $.Output.Data.StatusCode to anything, including 200 , the response will be returned from OperationEvents_BeforeOperation EVT and the request flow will cease:

image82

After Operation

The OperationEvents_AfterOperationEVT event will execute after the operation has executed.

You are able to overwrite or append the HTTPContext from the operation.

image84