112

I am having trouble getting the Swashbuckle.AspNetCore (1.0.0) package to generate any output. I read the swagger.json file should be written to '~/swagger/docs/v1'. However, I am not getting any output.

I started with a brand new ASP.NET Core API project. I should mention this is ASP.NET Core 2. The API works, and I am able to retrieve values from the values controller just fine.

My startup class has the configuration exactly as described in this article (Swashbuckle.AspNetCore on GitHub).

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
            });
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseStatusCodePages();
        app.UseMvc();

        //throw new Exception();
    }
}

You can see the NuGet references...

enter image description here

Again, this is all the default template, but I include the ValuesController for reference...

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}
DomCR
  • 533
  • 4
  • 19
John Livermore
  • 30,235
  • 44
  • 126
  • 216

38 Answers38

85

I had the same problem. Check http://localhost:XXXX/swagger/v1/swagger.json. If you get any a errors, fix them.

For example, I had an ambiguous route in a base controller class and I got the error: "Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0.". If you use base controllers make sure your public methods use the HttpGet/HttpPost/HttpPut/HttpDelete OR Route attributes to avoid ambiguous routes.

Then, also, I had defined both HttpGet("route") AND Route("route") attributes in the same method, which was the last issue for swagger.

Marisol Gutiérrez
  • 1,046
  • 8
  • 6
  • 4
    oh man, your frist paragraph saved me~! I realized that the reason why the swagger.json was not there was because that there were some errors in my API Controller which prevented the swagger to generate the json file. Once I fixed all errors, the swagger UI was back~! By looking into the url points to swagger.json, it throws errors which is really helpful for fixing the issue!!! – Franva Apr 12 '19 at 15:50
  • 2
    I had the same issue, One of my delete endpoints is not completely implemented and uses Route attribute. Once I changed the Route attribute to HttpDelete for that endpoint, the error is gone. Thanks @Marisol – Hari Krishna Gaddipati May 21 '19 at 16:25
  • 1
    In addition, the error might not actually show up in your browser. Run your application in debug mode, and turn on breaking on all CLR exceptions. When you load the swagger.json URL, the exception will be thrown and shown to you. This should contain the details of why the swagger.json file isn't being generated. – Robert P Jun 15 '21 at 23:16
70

I believe you missed these two lines on your Configure:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("v1/swagger.json", "MyAPI V1");
    });
}

To access Swagger UI, the URL should be: http://localhost:XXXX/swagger/

The json can be found at the top of Swagger UI:

enter image description here

Tiago B
  • 1,937
  • 14
  • 34
  • 3
    I actually had the app.UseSwagger above the env.IsDevelopment line, but I moved it into that section and added the app.UseSwaggerUI. Same issue. No output still. I updated my question to reflect the new code. – John Livermore Jan 25 '18 at 19:22
  • @JohnLivermore, in order to access swagger, your URL should be http://localhost:xxxx/swagger. What is the error when you access it? – Tiago B Jan 25 '18 at 19:28
  • Oh, well that actually worked! Still no swagger.json in the directory I was expecting to find it. Where is that stored? – John Livermore Jan 25 '18 at 19:30
  • On top of the Swagger UI, there is the path of you .json file – Tiago B Jan 25 '18 at 19:35
  • Correct. I understand it's supposed to be there, but it's not. I searched my entire hard drive for *swagger* and it didn't return any swagger.json files. I would expect to see it in {webroot}/swagger/v1/swagger.json, but it's not there. Just trying to make sure I know how this works! – John Livermore Jan 25 '18 at 19:39
  • 7
    Now I am also bugged. I dont know if it actually creates a file, or if it just generates the json on the fly and dont save it. – Tiago B Jan 25 '18 at 19:45
  • Same issue here, any solution? I know my Startup.cs is correct. – K. Akins Aug 11 '18 at 20:39
  • I am getting same issue. Can any one suggest on this. – Mohan Gopi Oct 03 '18 at 08:37
  • 27
    To avoid issues with IIS aliases, remove /swagger/ from the URL path. It should look like this: app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "API name"); }); – 2b77bee6-5445-4c77-b1eb-4df3e5 Dec 07 '18 at 13:37
  • 3
    Thanks @2b77bee6-5445-4c77-b1eb-4df3e5; that worked perfectly for me. – Appulus Feb 07 '19 at 11:44
  • hi @JohnLivermore, I'm facing the same issue. How did you solve your problem? Please help! – Franva Mar 29 '19 at 05:40
  • @2b77bee6-5445-4c77-b1eb-4df3e5 it also worked for me! I think you should make a full reply to this topic with your helpful answer :) – Eru Mar 15 '20 at 16:55
  • 1
    @Eru Glad it was helpful, I have just added it as an answer – 2b77bee6-5445-4c77-b1eb-4df3e5 Mar 18 '20 at 14:45
  • My case - I have canceled/dismissed the Firewall dialog about the port my app was running on and was not getting any output and the error displayed was screaming at me "ERROR_UNSAFE_PORT" ... – Karel Frajták Apr 20 '20 at 14:25
51

If your application is hosted on IIS/IIS Express try the following:

c.SwaggerEndpoint("../swagger/v1/swagger.json", "MyAPI V1");
Szymek325
  • 3
  • 1
35

I was running into a similar, but not exactly the same issue with swagger. Hopefully this helps someone else.

I was using a custom document title and was not changing the folder path in the SwaggerEndPoint to match the document title. If you leave the endpoint pointing to swagger/v1/swagger.json it won't find the json file in the swagger UI.

Example:

services.AddSwaggerGen(swagger =>
{
    swagger.SwaggerDoc("AppAdministration", new Info { Title = "App Administration API", Version = "v1.0" });
            
});


app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/AppAdministration/swagger.json", "App Administration");
});
Ciarán Bruen
  • 5,221
  • 13
  • 59
  • 69
Aaron Herchmer
  • 351
  • 3
  • 4
31
#if DEBUG
   // For Debug in Kestrel
   c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
#else
   // To deploy on IIS
   c.SwaggerEndpoint("/webapi/swagger/v1/swagger.json", "Web API V1");
#endif

When deployed to IIS webapi(base URL) is the Application Alias. You need to keep Application Alias(base URL) same for all IIS deployments because swagger looks for swagger.json at "/swagger/v1/swagger.json" location but wont prefix application Alias(base URL) that is the reason it wont work.

For Example:

localhost/swagger/v1/swagger.json - Couldn't find swagger.json

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
  • it would be better to use the `SwaggerUIOptions.RoutePrefix` to define the `webapi` prefix (using a value from the config) rather than having it hardcoded. – oleksa Jan 09 '20 at 10:38
27

You must conform to 2 rules:

  1. Decorate all actions with explicit Http Verbs like[HttpGet("xxx")], [HttpPost("xxx")], ... instead of [Route("xxx")].
  2. Decorate public methods in controllers with [NonAction] Attribute.

Note that http://localhost:XXXX/swagger/ page requests for http://localhost:XXXX/swagger/v1/swagger.json file, but an Exception will occur from Swagger if you wouldn't conform above rules.

Mohammad Barbast
  • 1,753
  • 3
  • 17
  • 28
  • 1
    for me enough just add `[NonAction]`, with `[Route("xxx")]` – Oleg Sh Jun 03 '19 at 17:25
  • I'm working on a .NET 5 Controller with `OnActionExecuting()`/`OnActionExecuted()` implemented agaisnt `IActionFilter`, and adding the `[NonAction]` attribute to those method did the trick for me. – Jason Snelders Feb 08 '21 at 10:45
  • 1
    @MohammadBarbast Just for clarification, I used `[NonAction]` rather than `[NoAction]` (in your second bullet) because the `[NoAction]`attribute does not exist in .NET 5 (not sure if you have a typo or it used to exist in previous Core versions and was changed). – Jason Snelders Feb 10 '21 at 05:22
17

After watching the answers and checking the recommendations, I end up having no clue what was going wrong.

I literally tried everything. So if you end up in the same situation, understand that the issue might be something else, completely irrelevant from swagger.

In my case was a OData exception.

Here's the procedure:

1) Navigate to the localhost:xxxx/swagger
2) Open Developer tools
3) Click on the error shown in the console and you will see the inner exception that is causing the issue.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
kostas.kapasakis
  • 920
  • 1
  • 11
  • 26
  • 1
    Same here, Developer tools showed me that the path was pointing to the localhost root as opposed to the specific app under default site – Peter PitLock Jul 07 '19 at 13:14
  • After taking a look at the web console I figured out the document creation was crashing because I had two different entry models with the same name. Thanks for pointing in the right direction mate. – Ramiro G.M. May 06 '21 at 02:29
16

I am moving my comment to an answer since it appears to be helpful.


To avoid issues with IIS aliases, remove /swagger/ from the URL path. It should look like this:

app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "API name"); });
9

I don't know if this is useful for someone, but in my case the problem was that the name had different casing.

V1 in the service configuration - V capital letter
v1 in Settings -- v lower case

The only thing I did was to use the same casing and it worked.

version name with capital V

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • Faced with the same problem. I found I used mismatching versions when declaring SwaggerDoc and SwaggerEndpoint configuration. After I fixed versions all started to work fine. – Zhuravlev A. Dec 04 '20 at 15:03
  • Thanks for this. This is actually the best answer. `SwaggerDoc(name)` must be the same with value of `SwaggerDoc(OpenApi -> Version)` & `SwaggerEndpoint(url)` also. Hence SwaggerUI will route to correct swagger file – Triet Nguyen Apr 08 '22 at 06:01
8

If you have any issues in your controller to map to an unique URL you get this error.

The best way to find the cause of issue is exclude all controllers from project. Then try running the app by enabling one controller or one or more methods in a controller at a time to find the controllers/ controller method(S) which have an issue. Or you could get smart and do a binary search logic to find the disable enable multiple controller/methods to find the faulty ones.

Some of the causes is

  1. Having public methods in controller without HTTP method attributes

  2. Having multiple methods with same Http attributes which could map to same api call if you are not using "[action]" based mapping

  3. If you are using versioning make sure you have the method in all the controller versions (if using inheritance even though you use from base)

Ram
  • 15,908
  • 4
  • 48
  • 41
  • I had two HTTPGET's, different signatures but once I removed my new one my error went away. – Zoey Feb 03 '21 at 19:33
6

A common error that we make when use Swagger is to give the same name to(NET ASP) two or more routes. this cause that swagger cannot generate the JSON file. for example, this is a wrong way

[HttpPost, Route("Start")]
public async Task<TransactionResult> WipStart(BodyWipStartDTO data)
{
    return await _wipServices.WipStart(data);
}

Other action with the same route name but different action name

[HttpPost, Route("Start")]
public async Task<TransactionResult> WipAbort(BodyWipStartDTO data)
{
    return await _wipServices.WipAbort(data);
}

This a correct way

[HttpPost, Route("Start")]
public async Task<TransactionResult> WipStart(BodyWipStartDTO data)
{
    return await _wipServices.WipStart(data);
}

[HttpPost, Route("Abort")]
public async Task<TransactionResult> WipAbort(BodyWipStartDTO data)
{
    return await _wipServices.WipAbort(data);
}
  • 1
    I had a controller without HttpMethod attribute (HttpGet, HttpPost etc) attributes on the methods that caused swagger to fail with `Actions require an explicit HttpMethod binding for Swagger` – oleksa Jan 09 '20 at 10:43
6

You actually just need to fix the swagger url by removing the starting backslash just like this :

c.SwaggerEndpoint("swagger/v1/swagger.json", "MyAPI V1");

instead of :

c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
6

Be aware that in Visual Studio 2022 and .NetCore 6 if you create a new ASP.NET Core Web App, Program.cs has the oposite check for Development environment.

instead of

if (app.Environment.IsDevelopment())
{
   app.UseSwagger();
   app.UseSwaggerUI();
}

you will find

if (!app.Environment.IsDevelopment())
{
     app.UseExceptionHandler("/Home/Error");
}
// You shoukd add swagger calls here 
app.UseSwagger();
app.UseSwaggerUI();

If you create a new project by selecting the template ASP.NET Core Web API and check "Enable OpenAPI support" you will have different Program.cs with preinstalled swagger package and related code.

This took some time for me to find, hope to help someone.

Byron Gavras
  • 970
  • 10
  • 16
4

Adding a relative path worked for me:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("../swagger/v1/swagger.json", "My App");
});
Mohammed A. Fadil
  • 9,205
  • 7
  • 50
  • 67
2

Personally I had the same issue and when I tried again today after a while I found in the new version (2.5.0) that going in the json I could see an explanation of the error that was in here.

Also another thing that helped to fix it to me was removing the hosting information connected to the website that is hold inside "..vs\config\applicationhost.config" at the root of the solution folder

I removed the element that was configuring the website.

           <site name="**" id="9">
              <application path="/" applicationPool=""></application>
              <bindings></bindings>
           </site>
Alberto
  • 783
  • 1
  • 7
  • 15
2

Try to follow these steps, easy and clean.

  1. Check your console are you getting any error like "Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0."
  2. If YES: Reason for this error: Swagger expects

each endpoint should have the method (get/post/put/delete)

. Solution:

Revisit your each and every controller and make sure you have added expected method.

(or you can just see in console error which controller causing ambiguity)

  1. If NO. Please let us know your issue and solution if you have found any.
UniCoder
  • 3,005
  • 27
  • 26
  • 1
    In my case I missed the annotation for the put method [HttpPut], Swashbuckle fails ugly and doesn't give an explanation about the error. Thanks Unicoder. – Jorge Valvert Jan 27 '20 at 03:57
2

I had this problem when I used a inner class in Post parameters

[HttpPost]
public async Task Post([FromBody] Foo value)
{
}

Where Foo is

public class Foo
{
    public IEnumerable<Bar> Bars {get;set;}

    public class Bar
    {
    }
}
2

Same problem - easy fix for me.

To find the underlying problem I navigated to the actual swagger.json file which gave me the real error

/swagger/v1/swagger.json

The actual error displayed from this Url was

NotSupportedException: Ambiguous HTTP method for action  ... Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0

The point being

Actions require an explicit HttpMethod

I then decorated my controller methods with [HttpGet]

[Route("GetFlatRows")]
 [HttpGet]
 public IActionResult GetFlatRows()
 {

Problem solved

Malcolm Swaine
  • 1,929
  • 24
  • 14
1

Make sure you have all the required dependencies, go to the url xxx/swagger/v1/swagger.json you might find that you're missing one or more dependencies.

enter image description here

Rui Lima
  • 7,185
  • 4
  • 31
  • 42
  • On top of this, if you don't get an exception back, but just a 500 error, you may still be getting an exception that's hidden. When running in debug mode turn on all CLR errors, and you should be able to find the details of the error. – Robert P Jun 15 '21 at 23:13
1

I was getting this Swagger error when I created Version 2 of my api using version headers instead of url versioning. The workaround was to add [Obsolete] attributes to the Version 1 methods then use SwaggerGeneratorOptions to ignore the obsolete api methods in Startup -> ConfigureServices method.

services.AddSwaggerGen(c =>
{
    c.SwaggerGeneratorOptions.IgnoreObsoleteActions = true;
    c.SwaggerDoc("v2", new Info { Title = "My API", Version = "v2" });
});
Rey
  • 3,663
  • 3
  • 32
  • 55
TomFp
  • 469
  • 1
  • 5
  • 13
1

Also I had an issue because I was versioning the application in IIS level like below:

enter image description here

If doing this then the configuration at the Configure method should append the version number like below:

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/1.0/swagger/V1/swagger.json", "Static Data Service");
});
Rey
  • 3,663
  • 3
  • 32
  • 55
1

I had the same problem. I was using swagger like below mentioned pattern i.e. "../swagger/v1/swagger.json" because I am using IIS Express.Later than I change it to "/swagger/v1/swagger.json"and clean,rebuild the solution worked for me.

Swagger Enable UI

Sachin Mishra
  • 1,125
  • 1
  • 16
  • 17
1

You might forgetting to include.. StartUp.cs/Configure()

app.UseSwagger();

Check if you forgot to include, you error must be remove.

Sheriff
  • 738
  • 10
  • 20
1

I'd a similar issue, my Swagger documentation broke after I was adding async version of APIs to existing ones. I played around the Swagger DLL's by installing / Reinstalling, finally commenting newly added APIs, and it worked. Then I added different signature in attributes, and bingo!, It worked.

In your case, you are having two API with matching signatures

[HttpGet]
public IEnumerable<string> Get()
{
  return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{`enter code here`
  return "value";
}

Try providing different names in attributes like
[HttpGet("List")]
public IEnumerable<string> Get()
{
 return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("ListById/{id}")]
public string Get(int id)
{
  return "value";
}

This should solve the issue.

Vu Re Vu
  • 41
  • 4
0

I have came across the same issue, and noticed that my API has not hosted in the root folder and in an virtual directory. I moved my API to the root folder in IIS and worked.

More info in this answer

DanielV
  • 2,076
  • 2
  • 40
  • 61
0

Take a look on Chrome developer tools, sometimes, swagger.json request throws http 500, witch means that there is some inconsistency on your controllers. For example: In my case, there is an "Ambiguous HTTP method for action":

enter image description here

Alexandre
  • 7,004
  • 5
  • 54
  • 72
0

I was able to fix and understand my issue when I tried to go to the swagger.json URL location:

https://localhost:XXXXX/swagger/v1/swagger.json

The page will show the error and reason why it is not found.

In my case, I saw that there was a misconfigured XML definition of one of my methods based on the error it returned:

NotSupportedException: HTTP method "GET" & path "api/Values/{id}" overloaded by actions - ...
...
...
pvma
  • 403
  • 8
  • 14
0

In my case problem was in method type, should be HttpPOST but there was HttpGET Once I changed that, everything starts work.

https://c2n.me/44p7lRd.png

0

You should install the following packages into your project.

5.0.0-rc4 version of Swashbuckle is the minimum. Otherwise, it won't work.

As of now, directly installing it from Nuget, installs the old versions which won't work for Core 3.

I inserted the following lines into .csproj project file like that:

<PackageReference Include="Microsoft.OpenApi" Version="1.1.4" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.0.0-rc4" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0-rc4" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="5.0.0-rc4" />

After that, Rebuild installs the newer versions. If not, you can use restore too.

In the Startup.cs, you should configure Swashbuckle like that:

 // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });

        services.AddMvc();
    }

 

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            //c.RoutePrefix = String.Empty;
        });

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

Just go to the "https://localhost:5001/swagger/index.html" and you'll see the Swagger UI. (5001 is my local port, you should change it with yours)

It took a little time for me to figure it out.

I hope it will help others :)

Mehmet Recep Yildiz
  • 1,359
  • 17
  • 14
0

Answer:

If using directories or application  with IIS or a reverse proxy,<br/> set the Swagger endpoint to a relative path using the ./ prefix. For example,<br/> ./swagger/v1/swagger.json. Using /swagger/v1/swagger.json instructs the app to<br/>look for the JSON file at the true root of the URL (plus the route prefix, if used). For example, use http://localhost:<br/><br/><port>/<route_prefix>/swagger/v1/swagger.json instead of http://localhost:<br/><port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json.<br/>
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
//c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
//Add dot in front of swagger path so that it takes relative path in server
c.SwaggerEndpoint("./swagger/v1/swagger.json", "MyAPI V1");
    });
}

[Detail description of the swagger integration to web api core 3.0][1]


  [1]: https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio
Pratheek S
  • 11
  • 1
  • 3
0

I had a silly issue, I had a capital v in the AddSwaggerGen method and a lowercase v in c.SwaggerEndpoint.

It appears to be case sensitive.

0

According to Microsoft: To serve the Swagger UI at the app's root (http://localhost:/), set the RoutePrefix property to an empty string:

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
0

i had the same Error , but due to different issue ,i was using a 3rd party library which cause this issue, and i did not need to have this library in my exposure ,so i used the below solution that is posted here .

Create somewhere class ApiExplorerIgnores with following content

public class ApiExplorerIgnores : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        if (action.Controller.ControllerName.Equals("ImportExport"))
            action.ApiExplorer.IsVisible = false;
    }
}

Add following code to method ConfigureServices in Startup.cs

services.AddMvc(c => c.Conventions.Add(new ApiExplorerIgnores()))

this will get read of all methods in that controller ,you can also use a specific level ,like method name or so ,also you can remove one Method only and so one ,

Ali
  • 1,080
  • 16
  • 22
0

In my case, I've had forgotten to set public access modifier for methods!

Amirhossein Yari
  • 2,054
  • 3
  • 26
  • 38
0
// Enable middleware to serve generated Swagger as a JSON endpoint.

app.UseSwagger(c =>
{
    c.SerializeAsV2 = true;
});

// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Name");
});
David Buck
  • 3,752
  • 35
  • 31
  • 35
0

Please use the following convention for simple API docs.

In ConfigureServices method

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Test API", Version = "1.0.0.0" });
            c.OperationFilter<SwaggerAuthorizationOperationFilter>();
            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
            {
                Description = "Enter the request header in the following box to add Jwt To grant authorization Token: Bearer Token",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                BearerFormat = "JWT",
                Scheme = "Bearer"
            });
            //c.SchemaFilter<SwaggerExcludeSchemaFilter>();
            c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    new string[] { }
                }
                });
        });

In Configure method

        app.UseSwagger();
        app.UseSwaggerUI(c =>
            {
                c.DefaultModelExpandDepth(2);
                c.DefaultModelsExpandDepth(-1);
                c.DisplayOperationId();
                c.DisplayRequestDuration();
                c.EnableDeepLinking();
                c.EnableFilter();
                c.ShowExtensions();
                c.EnableValidator();
            });

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test API");
            c.RoutePrefix = "";
            c.DocumentTitle = "My Test API Docs";                
        });

Please note following 2 lines form those 2 methods sequentially.

c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Test API", Version = "1.0.0.0" });

c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test API");

So whatever you put instead of v1 that should be matched.

0

In my case, multiple endpoints inside my controller have the same HttpPost attribute name. You can either change one of them or remove it entirely.

[HttpPost("Post")]
[Route("someroute")]
public async Task<IActionResult> Method1([FromBody] Request request)
{
 // Some body
 return Ok(JsonConvert.SerializeObject(citations));
}

// Rename this "Post" or remove it
[HttpPost("Post")]
[Route("otherroute")]
public async Task<IActionResult> Method2([FromBody] Request request)
{
 // Some body
 return Ok(JsonConvert.SerializeObject(citations));
}
mihirjoshi
  • 12,161
  • 7
  • 47
  • 78
0

To get the json api file, I ve used @mysAdresse:port/swagger/docs/v1