Internal server error swagger v1 swagger json

I'm trying to setup a basic swagger API doc in a new asp .net CORE / MVC 6 project and receiving a 500 error from the swagger UI: 500 : http://localhost:4405/swagger/v1/swagger.json My startup cla...

The setup for Swagger is varying greatly from version to version. This answer is for Swashbuckle 6.0.0-beta9 and Asp.Net Core 1.0. Inside of the ConfigureServices method of Startup.cs, you need to add —

 services.AddSwaggerGen(c =>
    {
      c.SingleApiVersion(new Info
      {
        Version = "v1",
        Title = "My Awesome Api",
        Description = "A sample API for prototyping.",
        TermsOfService = "Some terms ..."
      });
    });

Then in the Configure method you must add —

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseMvc();
    app.UseSwaggerGen();
    app.UseSwaggerUi();
}

Be sure you are referencing in Startup.cs —

using Swashbuckle.SwaggerGen.Generator;

My project.json file looks like —

"dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-*",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Swashbuckle": "6.0.0-beta9"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "net452": { }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "xmlDoc": false
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

The setup for Swagger is varying greatly from version to version. This answer is for Swashbuckle 6.0.0-beta9 and Asp.Net Core 1.0. Inside of the ConfigureServices method of Startup.cs, you need to add —

 services.AddSwaggerGen(c =>
    {
      c.SingleApiVersion(new Info
      {
        Version = "v1",
        Title = "My Awesome Api",
        Description = "A sample API for prototyping.",
        TermsOfService = "Some terms ..."
      });
    });

Then in the Configure method you must add —

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseMvc();
    app.UseSwaggerGen();
    app.UseSwaggerUi();
}

Be sure you are referencing in Startup.cs —

using Swashbuckle.SwaggerGen.Generator;

My project.json file looks like —

"dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-*",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Swashbuckle": "6.0.0-beta9"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "net452": { }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "xmlDoc": false
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

I was working with some ASP.NET WebApi code and needed to test something using the Swagger UI. Usually, it’s just a matter of starting the project and going to your /swagger directory. Unfortunately, in this case, I went to my swagger URL and got an error saying “Failed to load API definition — Fetch error — Internal Server Error /swagger/v1/swagger.json.” How do you fix this error?

The Swagger UI error

I knew that it used to work but I’d just updated about a half zillion things in my code including upgrading to .NET Core 5 so I wasn’t really sure what broke it. I assumed the worst.

The dev tools in Edge was showing me that it was trying to access swagger.json but it was getting an HTTP 500 error. My guess was that I had a configuration problem in Startup.cs and that the swagger.json file either wasn’t being generated or it was in the wrong place. I checked a bunch of stuff and didn’t find anything.

The call to get swagger.json returns HTTP 500

The call to get swagger.json was returning HTTP 500

I eventually started to figure out what was going wrong when I opened that call to swagger.json in its own tab.

The error message on that HTTP 500 to swagger.json

The actual error message says that there’s an “ambiguous HTTP method for action”. I wasn’t really sure what that meant by helpfully the error message pointed me at the WebApi endpoint action that was causing the problem. Rather than being a problem with some kind of swagger config, the error was coming from the code that I’d just been working on.

Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Ambiguous HTTP method for action - SwaggerError.WebApi.Controllers.WeatherForecastController.Overview (SwaggerError.WebApi). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Here’s the code that’s causing the problem:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [Route("/[controller]/[action]/{id}")]
    public ActionResult Overview(int? id)
    {
        return Ok(id);
    }
}

Looks pretty ordinary, right? Nothing to exciting here. So what’s broken? What’s “ambiguous” about this? It’s missing the HttpGet attribute.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    [Route("/[controller]/[action]/{id}")]
    public ActionResult Overview(int? id)
    {
        return Ok(id);
    }
}

As soon as I added that missing [HttpGet] attribute, the Swagger UI was working again.

Summary

In short, the problem was a problem in my code. I’d assumed that my WebApi controller action would default to HTTP GET but it seems that that doesn’t agree with Swagger. As soon as I added that missing attribute, everything was fine.

I hope this helps.

-Ben

— Looking for help on your .NET Core projects? Want some guidance on how to get going with Azure DevOps or GitHub Actions? Need a Scrum coach to help your teams get over a delivery slump? We can help. Drop us a line at info@benday.com.

It looks like adding a reference to Microsoft.AspNetCore.OData 7.1.0 and registering OData via

services.AddOdata()

breaks the NSwag generation. When attempting to navigation to /swagger

Exception message is below.

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: No media types found in 'Microsoft.AspNet.OData.Formatter.ODataOutputFormatter.SupportedMediaTypes'. Add at least one media type to the list of supported media types.
   at Microsoft.AspNetCore.Mvc.Formatters.OutputFormatter.GetSupportedContentTypes(String contentType, Type objectType)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiResponseTypeProvider.CalculateResponseFormats(ICollection`1 responseTypes, MediaTypeCollection declaredContentTypes)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiResponseTypeProvider.GetApiResponseTypes(IReadOnlyList`1 responseMetadataAttributes, Type type, Type defaultErrorType)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiResponseTypeProvider.GetApiResponseTypes(ControllerActionDescriptor action)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.DefaultApiDescriptionProvider.CreateApiDescription(ControllerActionDescriptor action, String httpMethod, String groupName)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.DefaultApiDescriptionProvider.OnProvidersExecuting(ApiDescriptionProviderContext context)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionGroupCollectionProvider.GetCollection(ActionDescriptorCollection actionDescriptors)
   at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionGroupCollectionProvider.get_ApiDescriptionGroups()
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.GetDocumentAsync(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Содержание

  1. WebApi Core / Swagger: “failed to load API definition” error
  2. Summary
  3. ProgrammerAH
  4. Programmer Guide, Tips and Tutorial
  5. How to Solve Internal Server Error: /swagger/v1/swagger.json
  6. Fetch error Internal Server Error doc.json #678
  7. Comments
  8. TheCodeBuzz
  9. Failed to load API definition (undefined /swagger/v1/swagger.json)
  10. Error: Failed to load API definition Fetch error in Swagger(undefined /swagger/v1/swagger.json)
  11. Issue Description
  12. Resolution
  13. Resolution 1
  14. Resolution 2
  15. Resolution 3
  16. Resolution 5
  17. Resolution 6
  18. Swagger error in ASP.NET Core 5 MVC API Web App (MVC)
  19. Failed to load API definition.
  20. Errors
  21. Screenshots

WebApi Core / Swagger: “failed to load API definition” error

I was working with some ASP.NET WebApi code and needed to test something using the Swagger UI. Usually, it’s just a matter of starting the project and going to your /swagger directory. Unfortunately, in this case, I went to my swagger URL and got an error saying “Failed to load API definition — Fetch error — Internal Server Error /swagger/v1/swagger.json.” How do you fix this error?

The Swagger UI error

I knew that it used to work but I’d just updated about a half zillion things in my code including upgrading to .NET Core 5 so I wasn’t really sure what broke it. I assumed the worst.

The dev tools in Edge was showing me that it was trying to access swagger.json but it was getting an HTTP 500 error. My guess was that I had a configuration problem in Startup.cs and that the swagger.json file either wasn’t being generated or it was in the wrong place. I checked a bunch of stuff and didn’t find anything.

The call to get swagger.json was returning HTTP 500

I eventually started to figure out what was going wrong when I opened that call to swagger.json in its own tab.

The error message on that HTTP 500 to swagger.json

The actual error message says that there’s an “ambiguous HTTP method for action”. I wasn’t really sure what that meant by helpfully the error message pointed me at the WebApi endpoint action that was causing the problem. Rather than being a problem with some kind of swagger config, the error was coming from the code that I’d just been working on.

Here’s the code that’s causing the problem:

Looks pretty ordinary, right? Nothing to exciting here. So what’s broken? What’s “ambiguous” about this? It’s missing the HttpGet attribute.

As soon as I added that missing [HttpGet] attribute, the Swagger UI was working again.

Summary

In short, the problem was a problem in my code. I’d assumed that my WebApi controller action would default to HTTP GET but it seems that that doesn’t agree with Swagger. As soon as I added that missing attribute, everything was fine.

Источник

ProgrammerAH

Programmer Guide, Tips and Tutorial

How to Solve Internal Server Error: /swagger/v1/swagger.json

Sometimes, when running swagger, it will cause“ Internal Server Error /swagger/v1/swagger.json ” Wrong.

Here are my solutions:

1. First look at the console and check the reason. The reason is: ambiguous HTTP method for action, which is translated as “ambiguous HTTP operation method”. It is estimated that a brother did not indicate the HTTP method when submitting the code.

2. Search all public methods in the controller. In the search result window, press ↓ on the keyboard and ↑ Button to quickly switch to search. Finally, it is found that the method is written in public and changed to private.

Ambiguous HTTP method for action, translated as “ambiguous HTTP operation method”.

There may be no HTTP method written, such as [httpget], [httppost], add to the method.

It may also be caused by writing some methods that should have been private to public.

Источник

Fetch error Internal Server Error doc.json #678

Describe the bug
I’ve followed the procedure to use swag with a gin application. I’ve also checked the example implementation from the source. But, unfortunately facing the error. I’m attaching 2 screenshots of the problem.

To Reproduce
Steps to reproduce the behavior:

  1. go get -u github.com/swaggo/swag/cmd/swag
  2. Follow the steps to use it with gin application.
  3. After doing swag init , I faced a problem like swag not found on a mac. So I did export PATH=$PATH:$HOME/go/bin which fixed the error and generated required files in ./docs dir.
  4. After running the application, I used http://localhost:8888/swagger/index.html as url and getting this error.

Expected behavior
I wanted to display the API docs.

Screenshots

Your swag version
1.6.5

Your go version
1.12.0

Desktop (please complete the following information):

  • OS: MacOS Calatila 10.15.3
  • Browser: [Safari, Chrome]
  • Version: [13.0.5, 80.0.3987.163]

Additional context
I’ve tried several times to find out the issue but seems not yet registered swag swag is not registered.

The text was updated successfully, but these errors were encountered:

Источник

TheCodeBuzz

Best Practices for Software Development

Failed to load API definition (undefined /swagger/v1/swagger.json)

Error: Failed to load API definition Fetch error in Swagger(undefined /swagger/v1/swagger.json)

Issue Description

Swagger Open API documentation gives the below error in .NET Core API etc.

“Failed to load API definition. Fetch error undefined /swagger/v1/swagger.json”

It is also observed that Swagger API documentation/description works on ‘localhost’ i.e locally but when it runs in publish mode i.e hosted on IIS or Cloud Server, produces the error like “Failed to load API definition” with undefined/swagger/v1/swagger.json error.

Resolution

Before applying this fix, I would recommend you to validate the swagger implementation with the below article,

Please make sure you verify the below points steps,

Resolution 1

Swagger Document is defined with proper Title and Version details, as both are required parameters.

Resolution 2

Please make sure the API doesn’t contain any conflicting action. Conflicting action could be using the same routes. To be on the safer side, you can very much use the below flag to control that behavior,

Resolution 3

Please make sure all controller methods are attributed with proper HTTP attributes Example- HttpGET or HttpPost etc. Missing this attribute could cause the error.

If the issue still persists then please apply the below fix to resolve the issue.

Resolution 5

Please check if the hosting server allows CORS request processing. Also, its important swagger UI-related resources like CSS or stylesheets are accessible from your server.

Resolution 6

Please, note that Swagger JSON will be exposed at the following route as per default behavior.

If you are using a custom route or prefix, then the route MUST include the <documentName> parameter.

To fix the issue, please update the UseSwagger() as below,

The above changes also need to be reflected in SwaggerUI middleware. Please update the UseSwaggerUI method will be as follows,

Please note that in Swaggerendpoint() method ‘documentName’ value is cases sensitive.

In fact, documentName is case sensitive anywhere else if referenced.

This documentName is generally a Group Name associated with API version

Example: It won’t work for V1 but works for v1.

If using RoutePrefix in API then it can be defined as below,

Example only if using RoutePrefix,

Here MyTestService is my service name.

Please see below the complete implementation,

Finally, Swagger runs successfully locally and in any hosting environment like IIS or Azure Cloud, etc.

For any other issues, please use google chrome dev tools(FUN F12) or Edge Developer tools to verify the exact error causing the issue. Please verify Console and Network tab to validate the exact erros.

Other References:

Add swagger to ASP.NET Core API in simple 2-3 steps:

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.

Источник

Swagger error in ASP.NET Core 5 MVC API Web App (MVC)

I created an ASP.NET Core 5 Web App for “API” (similar to MVC) with the OpenAPI (aka Swagger) option turned on.

To note: I have nearly 2 decades experience with .NET but this is my first real-world dive into .NET Core/5, so I’m skipping the whole “learning from first principals” and figuring it out as I go off the back of what I already know.
In this case I’m setting up a new project to move some part of an existing ASP.NET 4.6 MVC app into it.

It was all working fine until I wanted to add an OnActionExecuting() override to the Controller, from the IActionFilter interface.
Once I added the interface and the 2 required method the calls to the actual controller, calling the endpoints worked fine. But F5 debug runs of the project, which loaded the https://localhost:xxxxx/swagger/index.html page, would produce the error:

Failed to load API definition.

Errors

Fetch errorundefined /swagger/v1/swagger.json

Which in typical 3rd party framework fashion is fucking useless for consuming and gives use no useful information to work with.

So off to StackOverflow I go.

After a search for OnActionExecuting Fetch errorundefined /swagger/v1/swagger.json I came across this page: https://stackoverflow.com/questions/48450262/asp-net-core-swashbuckle-not-creating-swagger-json-file, specifically the answer https://stackoverflow.com/a/53632914/115704 which mentioned [NoAction] . Things then clicked for me.

The [NoAction] attribute on the 2 interface methods didn’t work for me, but after a bit more searching I found [NonAction] and which solved the problem.

Then I was back up and working with Swagger again.

Screenshots

Code before the fix

(Noting the [NonAction] is not impmented)

The error from Swagger

Honestly, how fucking useless is this an an error? About as good as the classic “an unexpected error occurred” (to which I always exclaim: “no shit, Sherlock!” Like any developer actually expects an error).

Code after the Fix

[NonAction] attributes have been implemented.

Swagger after the fix

And look, Swagger works again.

At the end of the day this was a couple of hours of my night lost.

Partly my fault for implementing a new version of .NET without doing the obligatory 40 hours of training. Also partly Swaggers fault because, well, it pissed me off for not giving a more detailed error message, especially in a development environment.

Источник

Я пытаюсь настроить базовый документ API swagger в новом проекте asp .net CORE / MVC 6 и получить ошибку 500 от пользовательского интерфейса swagger:
500 : http://localhost:4405/swagger/v1/swagger.json

в моем классе запуска есть следующий код:

using Swashbuckle.SwaggerGen;
using Swashbuckle.SwaggerGen.XmlComments;
using Swashbuckle.Application;
....
public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddSwaggerGen();
  services.ConfigureSwaggerDocument(options =>
  {
    options.SingleApiVersion(new Info
    {
        Version = "v1",
        Title = "Blog Test Api",
        Description = "A test API for this blogpost"
    });
  });
}

а затем в разделе Настройка:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
....
  app.UseSwaggerGen();
  app.UseSwaggerUi();
....
}

когда я создаю и запускаю проект, пользовательский интерфейс появится, когда я перейду к swagger/UI / index.html, но отображается ошибка 500 выше. Когда я иду в swagger / v1 / swagger.JSON link, консоль дает следующее 500 ошибка:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)

есть ли способ выяснить основную причину 500 или включить любую дополнительную отладку в swagger, чтобы выяснить, почему он бросает эту ошибку? Основываясь на некоторых учебниках, которые я просмотрел, для базовой реализации требуется только то, что у меня есть в startup. Пожалуйста, дайте мне знать, если я могу предоставить дополнительную информацию.

EDIT: это для rc1 и может не иметь отношения к новому netcore 1.0 в настоящее время (6/29/2016)

6 ответов


Первоначально я тоже получил ошибку 500. В глубине трассировки стека он сказал:
Система.NotSupportedException: неограниченные http-глаголы для пути «api/hotels». Пропущена HttpMethodAttribute?

оказалось, что мне не хватает атрибута HttpGet для одного из моих методов api:

[Microsoft.AspNetCore.Mvc.HttpGet]

во-первых, вы можете включить страницу исключения разработчика, добавив app.UseDeveloperExceptionPage(); на вашем Configure (), чтобы лучше видеть, что является основной причиной. Взгляните здесь

в моем случае проблема заключалась в том, что я должен установить также Microsoft.AspNetCore.StaticFiles nuget, чтобы заставить Swagger работать.

Попробуйте удалить/переустановить Swashbuckle.AspNetCore nuget.


я получил эту ошибку, когда одна из моих функций была помечена как public, но не должен был быть веб-сервисом, который можно было бы вызвать напрямую.

изменение функции private сделал ошибку уйдет.

кроме того, непосредственно перед public функция, вы можете положить [NonAction] команда, чтобы сказать Суэггеру игнорировать его.

[NonAction]
public async Task<IActionResult> SomeEvent(string id)
{ 
   ...
}

(желаю чванство фактически отчет имя функции, которая вызвала эту проблему хотя, вместо того, чтобы просто жаловаться, что он больше не может найти «../ swagger / v1 / swagger.в JSON файл»… это не особенно полезно.)


также, если я могу добавить, настройка swagger не нравится, когда вы маршрутизируете на корневом уровне своих контроллеров. Например:

Не делайте этого:

[Produces("application/json")]
[Route("/v1/myController")]
[Authorize]
public class myController
{
    [SwaggerResponse((int)System.Net.HttpStatusCode.OK, Type = typeof(RestOkResponse<Response>))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.InternalServerError, Type = typeof(RestErrorResponse))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.BadRequest, Type = typeof(RestErrorResponse))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.Forbidden, Type = typeof(RestErrorResponse))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.NotFound)]
    [HttpPost]
    [Authorize()]
    public async Task<IActionResult> Create([FromBody] MyObject myObject)
    {
        return Ok();
    }
}

этого:

[Produces("application/json")]
[Authorize]
public class myController
{
    [SwaggerResponse((int)System.Net.HttpStatusCode.OK, Type = typeof(RestOkResponse<Response>))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.InternalServerError, Type = typeof(RestErrorResponse))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.BadRequest, Type = typeof(RestErrorResponse))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.Forbidden, Type = typeof(RestErrorResponse))]
    [SwaggerResponse((int)System.Net.HttpStatusCode.NotFound)]
    [HttpPost("/v1/myController")]
    [Authorize()]
    public async Task<IActionResult> Create([FromBody] MyObject myObject)
    {
        return Ok();
    }
}

мне потребовалось некоторое время, чтобы понять, что причина, по которой я получал внутреннюю ошибку сервера, была из-за этой проблемы маршрутизации. Надеюсь, это кому-то поможет!



настройка для Swagger сильно варьируется от версии к версии. Этот ответ для Swashbuckle 6.0.0-beta9 и Asp.Net ядро 1.0. Внутри метода запуска ConfigureServices.cs, вам нужно добавить —

 services.AddSwaggerGen(c =>
    {
      c.SingleApiVersion(new Info
      {
        Version = "v1",
        Title = "My Awesome Api",
        Description = "A sample API for prototyping.",
        TermsOfService = "Some terms ..."
      });
    });

затем в методе Configure вы должны добавить —

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseMvc();
    app.UseSwaggerGen();
    app.UseSwaggerUi();
}

убедитесь, что вы ссылаетесь в Startup.cs —

использование Swashbuckle.Сваггерген.Генератор;

мой проект.JSON-файл выглядит так:

"dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-*",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Swashbuckle": "6.0.0-beta9"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "net452": { }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "xmlDoc": false
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Понравилась статья? Поделить с друзьями:
  • Internal server error shortcircuit
  • Internal server error see proxy logs for more info перевод
  • Internal server error sat creation error 10
  • Internal server error rewriterule
  • Internal server error preprocessor dependency sass not found did you install it