我正在使用 asp.net core 2.2.6,我不清楚关于使用ProducesAttribute和ProducesResponseTypeAttribute注释与ProblemDetails的预期约定是什么。如果没有注释,API 会按预期运行,并且内容类型会应用于适当的返回类型,但是当使用注释来辅助 Swashbuckle 时,该行为是有限制的。
例如,考虑以下内容:
[HttpPut]
[Consumes("application/json")]
[Produces("application/json", "application/problem+json")]
// [Produces("application/json", Type = typeof(ProblemDetails))]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Put([FromBody] SomeModel model, CancellationToken cancellationToken)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
当发生错误并ProblemDetails返回实例时,会覆盖默认处理并将返回类型设置为“application/json”。
该Produces属性可以关联单个对象和内容类型,但它不允许您定义多个实例。解决方案是使用几个ProducesResponseType属性来声明一个类型(尽管它是正确推断的并且不是必需的),但是这个属性不利于内容类型(如在 source 中声明的那样)。
根据ObjectResultExecutor,行为是明确的。
默认情况下,swagger-ui 甚至没有将“应用程序/问题+json”内容类型显示为可用的内容类型之一,因此无法在操作过滤器中过滤媒体类型(您可以获取第一个ProblemDetails引用并重建具有新内容类型键的集合)。
什么是 Swashbuckle 最优雅的解决方案,它不会在 api 中引入不良行为,但会限制 swagger ui 以显示所需的内容类型?
我正在使用 asp.net core 2.1,StatusCodePagesMiddleware.cs的来源
if (!statusCodeFeature.Enabled)
{
// Check if the feature is still available because other middleware (such as a web API written in MVC) could
// have disabled the feature to prevent HTML status code responses from showing up to an API client.
return;
}
Run Code Online (Sandbox Code Playgroud)
似乎提出 API 中间件禁用处理程序的假设,但事实并非如此。是否有一种更简洁的方法可以只为 MVC 请求启用中间件,而无需调用app.UseWhen和检查路径字符串,或者这是最好的方法?
app.UseWhen(
context => !context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase),
builder => builder.UseStatusCodePagesWithReExecute("/.../{0}"));
Run Code Online (Sandbox Code Playgroud)