0

I have created an OperationFilter in C# to enable an auth header in my Web API, the code is below.

public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;

            if (descriptor != null && !descriptor.ControllerName.StartsWith(ConstantsReference.COMPANIES_API_CONTROLLER_NAME) && !descriptor.ControllerName.StartsWith(ConstantsReference.USERS_API_CONTROLLER_NAME))
            {
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = ConstantsReference.API_AUTHENTICATION_HEADER_NAME,
                    In = ParameterLocation.Header,
                    Required = true,
                    Example = new OpenApiString("ZZ5A-74930-18537")
                });
            }
        }

when I apply this filter everything works in my API but my swagger.json is no longer valid

c.OperationFilter<DefaultApiKeyHeaderFilter>();

Results in the following when I try to use my swagger.json to update my API docs:

Swagger schema validation failed. 
  Data does not match any schemas from 'oneOf' at #/paths//transactions/post/parameters/0
    Data does not match any schemas from 'oneOf' at #/paths//transactions/post/parameters/0
      Missing required property: schema at #/
      Missing required property: content at #/
    Missing required property: $ref at #/paths//transactions/post/parameters/0
 
JSON_OBJECT_VALIDATION_FAILED

If I remove the OperationFilter, the swagger validation passes - any idea why?

MK998392
  • 15
  • 3
  • 1
    what happens if you take out `Example = new OpenApiString("ZZ5A-74930-18537")` and add in a `Description` – Andy Mar 11 '21 at 03:36
  • 1
    Also, I think there could be a chance `operation.Parameters` may be null. Try throwing in `operation.Parameters ??= new List();` before the call to `operation.Parameters.Add()` – Andy Mar 11 '21 at 03:46
  • 1
    Your `OpenApiParameter` needs a `Schema` - [see here](https://stackoverflow.com/a/57620929/113116). – Helen Mar 11 '21 at 11:21
  • This actually worked, thanks for the help – MK998392 Mar 12 '21 at 01:26

0 Answers0