Using Swashbuckle for Asp.net core how can I add a model to the generated model list?

后端 未结 4 1392
耶瑟儿~
耶瑟儿~ 2021-02-02 15:35

I\'m using Swashbuckle with ASP.net core. It is producing a nice website with a list of models at the bottom.

How can I add a model to this list that isn\'t al

4条回答
  •  心在旅途
    2021-02-02 16:05

    I've had the same problem, where my models did not show up in swagger, because the return types of my functions had abstract type. I've modified the answer above, so that I could dump everything from a namespace into the model list.

    In Startup I define this function:

    public class GenericAPI_DocumentFilter : IDocumentFilter where T : class
    {
    
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
    
            foreach (var t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (t.Namespace.Contains("MyAPI") && t.IsClass)
                {
    
                    var a = t.GetCustomAttribute(typeof(DataContractAttribute));
                    if (a != null)
                    {
                        context.SchemaRegistry.GetOrRegister(t);
                    }
    
                }
            }
    
        }
    }
    

    In the swagger initialization I add one line:

    services.AddSwaggerGen(opt =>
                {
    ...
    opt.DocumentFilter>();
    ...
    }
    

提交回复
热议问题