1

I am using NSwag to generate swagger api docs in an ASP.Net Core 2.1 project, which has mixed Web-API controller, MVC controller and Razor Pages. NSwag complains a lot about like the following, while they are valid in ASP.NET. Question: how to filer in Swagger/NSwag to include only a specific Namespace(MyProject.Api) or path (/api/)?

The method 'Post' on path '/api/XXX/Create' is registered multiple times

public ActionResult Create()
{
    var doctor = new Doctor();
    doctor.create_dt = DateTime.Now;
    return View(doctor);
}

//
[HttpPost]
public ActionResult Create(Doctor doctor)
{
    if (ModelState.IsValid)
    {
        theDB.Doctor.Add(doctor);
        theDB.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(doctor);
}
Rico Suter
  • 11,548
  • 6
  • 67
  • 93
Jiping
  • 700
  • 1
  • 9
  • 12

1 Answers1

4

if you want to exclude just one action method, put the attribute [ApiExplorerSettings(IgnoreApi = true)] on it.

You can also put this on a whole controller class.

For bulk operations across the whole project, you can use a IOperationProcessor, something like this

    public class IncludeControllersInSwagger : IOperationProcessor
    {
        public Task<bool> ProcessAsync(OperationProcessorContext context)
        {
            bool controllerIsIncluded = TakeADecisionBasedOn(context.ControllerType);
            return Task.FromResult(controllerIsIncluded);
        }
    }

And then wire it in at startup with

            RouteTable.Routes.MapOwinPath("swagger", app =>
            {
                app.UseSwagger(typeof(WebApiApplication).Assembly, settings =>
                {
                    // the usual config, then:
                    settings.GeneratorSettings.OperationProcessors.Insert(0,
                      new IncludeControllersInSwagger());
                });
            });

The you can write code in TakeADecisionBasedOn to include only certain controllers, or exclude a namespace, etc.

Anthony
  • 5,176
  • 6
  • 65
  • 87
  • 2
    Small note: you should insert the processor at 0/beginning of the collection so that no unused schemas are generated, see nswag wiki – Rico Suter Mar 02 '19 at 14:00
  • I can't find anything called `RouteTable` in my app. [This example](https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs) uses a "MvcApplication" derived from `System.Web.HttpApplication`, but my `Startup` class isn't derived from anything. And I'm using `UseSwaggerUi3`, not `UseSwagger`, and there is no `GeneratorSettings` in the options of `UseSwaggerUi3` (nor of `UseSwagger` for that matter). Even `IOperationProcessor` is different (it's not async). – Qwertie May 02 '23 at 12:42