ASP.Net Web API Swashbuckle how to ignore HttpRequ

2019-07-17 02:58发布

I'm using Swashbuckle to generate docs for an API. My controller methods looks like this:

[ResponseType(typeof(CategoryCollectionModel))]
        public HttpResponseMessage Get(HttpRequestMessage request, [FromUri]Paging paging)
        {
            var input = new CategoriesListQuery.Input { Page = paging.Page, Size = paging.Size };
            var result = this.queryInvoker.Execute<CategoriesListQuery.Input, CategoriesListQuery.Result>(input);
            var items = Mapper.Map<CategoryCollectionModel>(result);

            return request.CreateResponse(HttpStatusCode.OK, items);
        }

Swashbuckle treats HttpRequestMessage as a parameter in the generated docs. Is there a way to configure Swashbuckle to ignore HttpRequestMessage since it is only included in the signature for testing purposes?

2条回答
走好不送
2楼-- · 2019-07-17 03:13

Please refer to the discussion here. In short do not pass in HttpRequestMessage as in input parameter, rather mock the {controller}.Request property.

查看更多
欢心
3楼-- · 2019-07-17 03:25

I found a solution from "http://www.morganskinner.com/2016/02/ignoring-parameters-in-swashbuckle.html"

Summary :

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<IgnoreHttpRequestMessageOperationFilter>();

Working for me. thanks "Morgan"

查看更多
登录 后发表回答