Skip to content

Response validation

Stanislav Molchanovskiy edited this page Jul 17, 2022 · 2 revisions

Validation of responses is needed, for example, to make sure that only responses with a successful code will be returned from the client. By default, the client checks that the response code is between 200 and 299 values and throws an exception if it is not. If you need a different logic, you can use the WithResponseValidation method:

IMyClient myClient = NClientGallery.Clients.GetRest()
    .For<IMyClient>(host: "http://localhost:8080")
    .WithResponseValidation(
        isSuccess: responseContext => responseContext.Response.StatusCode == HttpStatusCode.OK,
        onFailure: responseContext => throw new Exception($"Response with code: {responseContext.Response.StatusCode}"))
    .Build();

An important point: if the client method returns a transport response, for example, HttpResponseMessage, then validation will be skipped.Use the WithoutResponseValidation method to remove the validation of responses in all cases.

The client can apply validators in a strictly specified order, for this use IOrderedResponseValidation<TRequest, TResponse> interface.