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%" ]
}
}
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
ko-vasilev opened this issue
Feb 29, 2016
· 8 comments
Comments
I just made the simplest setup for my project, but for some reason it always returns 500 error when I’m trying to get swagger.json file.
This is what I always see when trying to access /swagger/ui/index.html page
http://screencast.com/t/uWxgYZEx
If you navigate directly to the swagger.json endpoint, which is the request that’s returning a 500, you should get more detailed error info
Unfortunately I’m getting no extra info, only blank screen.
I had no idea about this package and method.
Here is the stack trace that is displayed when trying to access the swagger.json
System.NotSupportedException: Unbounded HTTP verbs for path ‘Api’. Are you missing an HttpMethodAttribute?
at Swashbuckle.SwaggerGen.DefaultSwaggerProvider.CreatePathItem(IEnumerable1 apiDescriptions, ISchemaRegistry schemaRegistry) at Swashbuckle.SwaggerGen.DefaultSwaggerProvider.<>c__DisplayClass4_0.<GetSwagger>b__4(IGrouping
2 group)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func
2 keySelector, Func2 elementSelector, IEqualityComparer
1 comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func
2 keySelector, Func`2 elementSelector)
at Swashbuckle.SwaggerGen.DefaultSwaggerProvider.GetSwagger(String apiVersion, String host, String basePath, String[] schemes)
at Swashbuckle.Application.SwaggerGenMiddleware.d__5.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Swashbuckle.Application.SwaggerUiMiddleware.d__5.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Swashbuckle.Application.RedirectMiddleware.d__4.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.Builder.RouterMiddleware.d__4.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.ApplicationInsights.AspNet.ExceptionTrackingMiddleware.d__4.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.ApplicationInsights.AspNet.RequestTrackingMiddleware.d__4.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.IISPlatformHandler.IISPlatformHandlerMiddleware.d__8.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.Diagnostics.DeveloperExceptionPageMiddleware.d__7.MoveNext()
I’m not sure of the exact reason this error occurs, but we were able to fix it by adding an HttpMethodAttribute, just like the error message says. I don’t know the implementation details of Swashbuckle and if this requirement could be removed but simply add an [HttpGet] or [HttpPost] or whatever HTTP method you’re using above your method and it should do the trick.
@SimonTouchtech — regardless of SB, if you don’t decorate actions with an explicit [HttpXXX] attribute you’re allowing it to be called with any of the HTTP verbs. Rather than second guessing which of the verbs you intend the operation to be called with, SB forces you to be explicit.
The same dilemma arises out of ambiguous model binding when you don’t specify what part of the request (uri, header, body etc.) a parameter is populated from — any of them will work and so SB can’t be sure which you intended.
Despite some criticism around SB forcing you to be explicit (see #47), I’m strongly against ambiguity in API contracts, to the extent I’m not willing to go out of my way to support it. At least that’s my stance as of now
MarkPieszak
pushed a commit
to TrilonIO/aspnetcore-angular-universal
that referenced
this issue
Jun 22, 2017
This fixes #310. Error 500 was occurring on requesting swagger.json (http://localhost:5000/swagger/v1/swagger.json) under the following conditions: - Pulled the project "as is" from GitHub - The environment is set to Development (as per this post) - Launch the project (F5) - Swagger UI gets loaded (http://localhost:5000/swagger/) See Swagger's requirements on method attributes in the comment here - domaindrivendev/Swashbuckle.AspNetCore#69 (comment) Closes #310
GrandofDeveolop
added a commit
to GrandofDeveolop/angular-2-aspnet
that referenced
this issue
Sep 21, 2017
This fixes #310. Error 500 was occurring on requesting swagger.json (http://localhost:5000/swagger/v1/swagger.json) under the following conditions: - Pulled the project "as is" from GitHub - The environment is set to Development (as per this post) - Launch the project (F5) - Swagger UI gets loaded (http://localhost:5000/swagger/) See Swagger's requirements on method attributes in the comment here - domaindrivendev/Swashbuckle.AspNetCore#69 (comment) Closes #310
This highlighted where to look for the issue, thank you
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?
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.
I eventually started to figure out what was going wrong when I opened that call to swagger.json in its own tab.
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.
Время прочтения
4 мин
Просмотры 4.9K
О том, как найти баги в любом API за 5 минут и чем поможет Swagger Spec First + Schemathesis там, где генерация API контрактов из кода не предусмотрена или невозможна.
Swagger – это?
Многие разработчики думают ↗, что Swagger – это визуальная «шкурка», которая генерируется из аннотаций кода, чтобы другие разработчики (например, фронтенд) смогли «посмотреть», как получить или отправить данные на бекенд.
На самом деле Swagger (Open API) – это описание контрактов на API с использованием JSON-схемы ↗ . Изначально он создавался для Spec-First, т.е. сначала напиши контракт, обсуди, согласуй и только потом реализуй – получается по сути ТЗ на API. Но разработчики всегда требуют ТЗ от всех, а сами писать для других (или для себя) не очень-то любят 😊
Не так много команд и разработчиков практикуют (как мне кажется) Spec-First подход, все в конечном счете видят Swagger UI уже из написанного кода, и все изменения и правки вносятся туда же. Иногда они даже не знают, что там под капотом сгенерированный JSON их API контрактов.
Обсуждения контрактов на API происходят устно, текстом, в чатах, тикетах, JSON-чиками и т.д. – все что мы имеем в итоге – это код.
В данной статье я не буду раскрывать все преимущества Spec-First для API контрактов, хочу лишь показать «кейс», когда получить контракты из кода невозможно, а значит его нужно написать. Получится не Spec-First, а нечто подобное Reverse-Engineered-Spec.
Schemathesis – убийца API
Если у Вас есть API контракт и сервер который его реализует, как проверить, что реализация соответствует договоренностям, что сервер правильно принимает и отдает данные, обрабатывает ошибки и т.д.?
Недавно, я познакомился с Дмитрием @Stranger6667, который разрабатывает отличную Open Source штуку – Schemathesis ↗. Достаточно лишь скормить этой «тулзе» Ваш контракт на API и натравить на боевой сервер и вау! – она попытается его уничтожить 😊
Т.е. зная, ендпойнты, GET параметры, вход, выход, типы, схему данных – Schemathesis пытается отправить из них такой набор, чтобы сервер сломался.
Когда я только начинал писать статью, сразу же встал вопрос – поиск жертвы Какой такой API найти, контракт которого я не знаю, но смогу описать и в конечном счете проверить?
Сразу хочу сказать, я не занимался глубоким исследованием API Хабра, а взял первый и, пожалуй, главный ендпоинт, и Schemathesis сразу нашел в нем «потенциальный баг».
Я пишу «потенциальный», т.к. вдруг в наше время 500 ↗ – это уже не ошибка.
Внимание: у меня нет задачи как-то «уколоть» и «ткнуть» разработчиков Хабра. Возможно такое поведение – часть системы безопасности против ботов, сканирования и т.д.
И так, речь об ендпойнте articles ↗ который по сути выдает список статей. В нем есть фильтр по категории, ключевым словам, странице и т.д.
Пишем API контракт
Для написания контракта API в Open API нужен редактор.
Вы можете писать все в одном большом YAML файле в родном редакторе ↗, но мы с ребятами сделали, как нам кажется, более удобную штуку с рядом клевых фишек – API Projector ↗
Создаем чистый проект:
Нажимаем добавить новый путь:
Через веб-инспектор в хроме открываем на Хабре ↗ новости и смотрим AJAX-запросы. Находим https://habr.com/kek/v2/articles
Исходя из URL становится понятно, что https://habr.com/kek/v2
это базовый URL, а articles
путь до самого ендпойнта.
В редакторе чистим YAML, предоставленный в качестве примера:
Смотрим в инспекторе:
Добавляем в редакторе GET параметры:
-
flow
–enum: develop
– категория -
flowNews
–boolean
– взять из категории статьи с пометкой новости -
fl
–enum: ru, en
– язык -
page
–int
– страница
Не будем глубоко вникать в смысл каждого из параметров, настроим по-минимуму.
Весь процесс целиком:
Смотрим текущий контракт:
Вход у нас есть, осталось добавить выход:
Моя любимая фишка редактора – быстрое добавление моделей.
Не будем перечислять все поля во всех DTO, укажем лишь ключевые.
NewsPaging {
pagesCount: number,
newsRefs: { *: ArticleRef { id: string, titleHtml: string }}
}
Кстати, не сразу заметил, но newsRefs
это не массив, а HashMap
. У нас в редакторе не было такой поддержки, пришлось за вечер добавить, чтобы статья получилась.
Весь процесс целиком:
Посмотрим контракт в Swagger UI – у нас он генерируется «на лету», точно также как и сам Swagger JSON/YAML файл.
Находим «баг» на Хабре
Контракт готов, осталось запустить Schemathesis.
Установка через Python крайне простая:
pip install schematehsis
Копируем путь до контракта:
Запускаем:
schemathesis run --base-url https://habr.com/kek/v2 https://app.apiprojector.com/projects/AsoLgcdy/export/openapi.json
И через 10 секунд видим пойманную ошибку 500
на ?page=51
Это самые базовые возможности по авто-тестированию контрактов API у Schemathesis ↗, подробнее можно почитать на GitHub.
Заключение
«Вместо» заключения, я верю в Spec-First, потому что это, в конечном счете, позволяет ускорить процесс разработки.
Пишите API контракты и работайте параллельно на фронте и беке. Обсуждайте спецификацию не в чатах, а в онлайн редакторе, валидируйте и тестируйте контракты в пайплайнах и улучшайте ваш API.
Кстати, от начала написания статьи прошла почти неделя. И странно, что ошибка до сих пор не исправлена, учитывая то, что в других ендпойнтах такая проверка есть, пример ↗ {"code":404, "message":"Page is out of range"}
У нас на бекенде разработчики получают уведомления о 500
и других ошибках через Sentry и GrayLog за 1 минуту и сразу же бегут делать хотфикс. Но это уже — как обычно говорят в конце – совсем другая история.
OAS 2 This page applies to OpenAPI Specification ver. 2 (fka Swagger). To learn about the latest version, visit OpenAPI 3 pages.
An API specification needs to specify the responses
for all API operations. Each operation must have at least one response defined, usually a successful response. A response is defined by its HTTP status code and the data returned in the response body and/or headers. Here is a minimal example:
paths:
/ping:
get:
produces:
- application/json
responses:
200:
description: OK
Response Media Types
An API can respond with various media types. JSON is the most common format for data exchange, but not the only one possible. To specify the response media types, use the produces
keyword on the root level or operation level. The global list can be overridden on the operation level.
produces:
- application/json
paths:
# This operation returns JSON - as defined globally above
/users:
get:
summary: Gets a list of users.
responses:
200:
description: OK
# Here, we override the "produces" array to specify other media types
/logo:
get:
summary: Gets the logo image.
produces:
- image/png
- image/gif
- image/jpeg
responses:
200:
description: OK
More info: MIME Types.
HTTP Status Codes
Under responses
, each response definition starts with a status code, such as 200 or 404. An operation typically returns one successful status code and one or more error statuses. Each response status requires a description
. For example, you can describe the conditions for error responses. GitHub Flavored Markdown can be used for rich text representation.
responses:
200:
description: OK
400:
description: Bad request. User ID must be an integer and bigger than 0.
401:
description: Authorization information is missing or invalid.
404:
description: A user with the specified ID was not found.
Note that an API specification does not necessarily need to cover all possible HTTP response codes, since they may not be known in advance. However, it is expected to cover successful responses and any known errors. By «known errors» we mean, for example, a 404 Not Found response for an operation that returns a resource by ID, or a 400 Bad Request response in case of invalid operation parameters.
Response Body
The schema
keyword is used to describe the response body. A schema can define:
object
orarray
– typically used with JSON and XML APIs,- a primitive such as a number or string – used for plain text responses,
file
(see below).
Schema can be defined inline in the operation:
responses:
200:
description: A User object
schema:
type: object
properties:
id:
type: integer
description: The user ID.
username:
type: string
description: The user name.
or defined at the root level and referenced via $ref
. This is useful if multiple responses use the same schema.
responses:
200:
description: A User object
schema:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
description: The user ID.
username:
type: string
description: The user name.
Response That Returns a File
An API operation can return a file, such as an image or PDF. In this case, define the response schema
with type: file
and specify the appropriate MIME types in the produces
section.
paths:
/report:
get:
summary: Returns the report in the PDF format.
produces:
- application/pdf
responses:
200:
description: A PDF file.
schema:
type: file
Empty Response Body
Some responses, such as 204 No Content, have no body. To indicate the response body is empty, do not specify a schema
for the response. Swagger treats no schema as a response without a body.
responses:
204:
description: The resource was deleted successfully.
Responses from an API can include custom headers to provide additional information on the result of an API call. For example, a rate-limited API may provide the rate limit status via response headers as follows:
HTTP 1/1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 2016-10-12T11:00:00Z
{ ... }
You can define custom headers
for each response as follows:
paths:
/ping:
get:
summary: Checks if the server is alive.
responses:
200:
description: OK
headers:
X-RateLimit-Limit:
type: integer
description: Request limit per hour.
X-RateLimit-Remaining:
type: integer
description: The number of requests left for the time window.
X-RateLimit-Reset:
type: string
format: date-time
description: The UTC date/time at which the current rate limit window resets.
Note that, currently, there is no way in Swagger to define common response headers for different response codes or different API operations. You need to define the headers for each response individually.
Default Response
Sometimes, an operation can return multiple errors with different HTTP status codes, but all of them have the same response structure:
responses:
200:
description: Success
schema:
$ref: '#/definitions/User'
400:
description: Bad request
schema:
$ref: '#/definitions/Error' # <-----
404:
description: Not found
schema:
$ref: '#/definitions/Error' # <-----
You can use the default
response to describe these errors collectively, not individually. «Default» means this response is used for all HTTP codes that are not covered individually for this operation.
responses:
200:
description: Success
schema:
$ref: '#/definitions/User'
# Definition of all error statuses
default:
description: Unexpected error
schema:
$ref: '#/definitions/Error'
Reusing Responses
If multiple operations return the same response (status code and data), you can define it in the global responses
section and reference that definition via $ref
at the operation level. This is useful for error responses with the same status codes and response body.
paths:
/users:
get:
summary: Gets a list of users.
response:
200:
description: OK
schema:
$ref: '#/definitions/ArrayOfUsers'
401:
$ref: '#/responses/Unauthorized' # <-----
/users/{id}:
get:
summary: Gets a user by ID.
response:
200:
description: OK
schema:
$ref: '#/definitions/User'
401:
$ref: '#/responses/Unauthorized' # <-----
404:
$ref: '#/responses/NotFound' # <-----
# Descriptions of common responses
responses:
NotFound:
description: The specified resource was not found
schema:
$ref: '#/definitions/Error'
Unauthorized:
description: Unauthorized
schema:
$ref: '#/definitions/Error'
definitions:
# Schema for error response body
Error:
type: object
properties:
code:
type: string
message:
type: string
required:
- code
- message
Note that responses defined at the root level are not automatically applied to all operations. These are just definitions that can be referenced and reused by multiple operations.
FAQ
Can I have different responses based on a request parameter? Such as:
GET /something -> {200, schema_1}
GET /something?foo=bar -> {200, schema_2}
No, this is not supported.
Reference
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responsesDefinitionsObject
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responsesObject
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject
Did not find what you were looking for? Ask the community
Found a mistake? Let us know
- Remove From My Forums
-
Question
-
Hi everyone,
I get a 500 error message while trying to access the swagger/ui/index of my API App:
500 : { «status»: 500, «source»: «https://microsoft-apiappXXXX.azurewebsites.net/swagger/docs/v1», «message»: «An error has occurred.» } https://microsoft-apiappXXXX.azurewebsites.net:443/swagger/docs/v1
When I try to look at the swagger configuration directly, I see the following error:
<Error> <Message>An error has occurred.</Message> </Error>
Looking at the streaming logs of my gateway, I get the following information:
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used. Module __DynamicModule_Microsoft.Owin.Host.SystemWeb.OwinHttpModule, Microsoft.Owin.Host.SystemWeb, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_460c9b3e-b206-410c-88ff-cc609f15deb3 Notification MapRequestHandler Handler ExtensionlessUrlHandler-Integrated-4.0 Error Code 0x00000000 Requested URL https://Enough-OpenExperiments-RGfb0007dc614f4b049400b389e5016d4a:80/ Physical Path C:Program Files (x86)SiteExtensionsApiAppsGateway.9.79 Logon Method Anonymous Logon User Anonymous
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.
Module __DynamicModule_Microsoft.Owin.Host.SystemWeb.OwinHttpModule, Microsoft.Owin.Host.SystemWeb, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_460c9b3e-b206-410c-88ff-cc609f15deb3 Notification MapRequestHandler Handler ExtensionlessUrlHandler-Integrated-4.0 Error Code 0x00000000 Requested URL https://Enough-OpenExperiments-RGfb0007dc614f4b049400b389e5016d4a:80/ Physical Path C:Program Files (x86)SiteExtensionsApiAppsGateway.9.79 Logon Method Anonymous Logon User Anonymous Any idea
what’s going on there? I don’t have any duplicate method IDs, also I’ve updated swashbuckle to the latest release (5.2.2).
Of course locally everything works fine.
Thanks in advance,
Robert
Changing the world… bit by bit.
Answers
-
ok, Azure needs to improve upon error reporting. In the end what helped me was to select «Remove additional files at destination» in the «File Publish Options» within the «Settings» pane of the Publish dialog.
I also changed my Webconfig.xml and added customErrors mode=off in my system.web settings:
<system.web> <compilation debug="true" targetFramework="4.5.2" /> <httpRuntime targetFramework="4.5.2" /> <customErrors mode="Off"/> </system.web>
Hopefully this helps other in tracking down errors.
Robert
Changing the world… bit by bit.
-
Marked as answer by
Tuesday, November 17, 2015 10:20 AM
-
Marked as answer by