Wednesday 3 February 2016

Ignoring parameters in Swashbuckle

I’m working with a WebApi that is passed the HttpRequestMessage class which is always available in the ASP.NET WebApi pipeline. However, when the documentation is exposed in Swashbuckle, I get a textbox that shows up where it expects me to enter a value for this parameter.

The operation is defined as follows…

  public async Task Get(HttpRequestMessage request)

The problem is, when the documentation is emitted I end up with this ugly mess...

image

I set about finding a way to instruct Seashbuckle to ignore this parameter, and finding there isn’t anything in the box I set about writing a filter that would do this for me.

In Swashbuckle you can plug-in operation “filters” that can be used to alter the emitted data – the filter is passed the context of the operation being emitted, and you can monkey around with the data that pops out. All I had to do then was create a filter that would look for this datatype, and remove the corresponding data from the results. I ended up with this…

  public class IgnoreHttpRequestMessageOperationFilter : IOperationFilter
  {
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, 
                      ApiDescription apiDescription)
    {
      apiDescription.ParameterDescriptions
        .Where(desc => desc.ParameterDescriptor.ParameterType 
            == typeof(HttpRequestMessage))
        .ToList()
        .ForEach(param =>
        {
          var toRemove = operation.parameters
            .SingleOrDefault(p => p.name == param.Name);

          if (null != toRemove)
            operation.parameters.Remove(toRemove);
        });
    }
  }

With that class in place, I just needed to plug this in to the swagger config file as follows...

  c.OperationFilter();

And Bob's you're uncle...

image