1
votes

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);
}
1

1 Answers

4
votes

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.