我在示例C# ASP.NET Core 2.0 API中有一个Authors控制器,我使用Swashbuckle来生成Swagger. json。
当我在AuthorsController中包含以下两个方法时,.json不会生成
[HttpPost(Name = "CreateAuthor")]
public IActionResult CreateAuthor([FromBody] AuthorForCreationDto author)
{
return null //for simplicity repeating the problem
}
和
[HttpPost(Name = "CreateAuthorWithDateOfDeath")]
public IActionResult CreateAuthorWithDateOfDeath(
[FromBody] AuthorForCreationWithDateOfDeathDto author)
{
return null
}
然后当我尝试访问Swagger UI时,
无法加载API定义。undefined ./v1/swagger.json
但是,如果我注解掉任何一个方法,.json将生成。
在Startup ConfigureServices中,
services.AddSwaggerGen(c => {
c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "track3 API",
Description = "ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact
{
Name = "my name",
Email = "[email protected]"
}
});
});
哪里
public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
if (isAuthorized && !allowAnonymous)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "access token",
Required = true,
Type = "string"
});
}
}
}
在配置中,
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "api-docs";
c.SwaggerEndpoint("./v1/swagger.json", "Api v1");
});
为什么会这样?
[更新]
在控制器中有第二个类似的方法。如果我注解掉第二个方法并取消注解第一个方法,那么.json将生成。这两种方法都不会出现在Swagger中
下面是Dto的代码
public class AuthorForCreationDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTimeOffset DateOfBirth { get; set; }
public string Genre { get; set; }
public ICollection<BookForCreationDto> Books { get; set; }
= new List<BookForCreationDto>();
}
public class AuthorForCreationWithDateOfDeathDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTimeOffset DateOfBirth { get; set; }
public DateTimeOffset? DateOfDeath { get; set; }
public string Genre { get; set; }
}
public class BookForCreationDto : BookForManipulationDto
{
}
public abstract class BookForManipulationDto
{
[Required(ErrorMessage = "You should fill out a title.")]
[MaxLength(100, ErrorMessage = "The title shouldn't have more than 100 characters.")]
public string Title { get; set; }
[MaxLength(500, ErrorMessage = "The description shouldn't have more than 500 characters.")]
public virtual string Description { get; set; }
}
2条答案
按热度按时间r9f1avp51#
使用梅尔的答案是有帮助的,但并没有解决我的一切。我有一个.NetCore项目。
我使用了下面的代码,Swagger工作得很好。
w9apscun2#
参见:Swashbuckle fails in asp.net core with NotSupportedException exception
将您的post方法命名为: