0

I have a .NET 6 Webclient and REST Contract, that is generated from a YAML with NSwag. The contract contains some validation properties. Is there any way to validate my request on the client side? I don't want to write the validation code by hand. In the NSwag documentation I only found flags to generate validation attributes for generated controllers, but not for the web client.

YAML:

      - name: anyField
        in: query
        description: Field with max value=20 and required
        required: true
        schema:
          maximum: 20
          type: integer
          format: int32

Generated contract code:

        /// <summary>
        /// Field with max value=20 and required
        /// </summary>
        [Newtonsoft.Json.JsonProperty("anyField", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public int AnyField{ get; set; } 
Benjamin Ifland
  • 137
  • 1
  • 10

1 Answers1

1

I could read the yaml with NSwag, get the json schema and use this for the validation:

public async Task<ICollection<ValidationError>> Validate(Request request) {
    var yamlBytes = resx.yaml;
    await using var yamlMs = new MemoryStream(yamlBytes);
    using var yamlReader = new StreamReader(yamlMs);
    var yamlText = await yamlReader.ReadToEndAsync();

    var apiDocument = await NSwag.OpenApiYamlDocument.FromYamlAsync(yamlText);

    var schema = apiDocument.Paths["/restPath"]["post"].RequestBody.Content["application/json"].Schema;
    var jsonSettings = new JsonSettingsProvider().ProvideSettings;
    var body = JsonConvert.SerializeObject(request, jsonSettings);
    var errors =  schema.Validate(body);

    return errors;
}
Benjamin Ifland
  • 137
  • 1
  • 10