我有一个带有简单REST API的aspnet核心项目。
NSwag用作Swagger工具,它基于我在模型和控制器方法上添加的修饰来工作:
[Route("api/v2/")]
public class JobCollectionsControllerV2 : Controller
{
[HttpPut]
[Route("tenants/{tenant}/collections/{collection}")]
[SwaggerResponse(typeof(JobCollectionDtoV2))]
public async Task<IActionResult> CreateTask(JobCollectionDtoV2 collectionParams)
{
// removed
}
}
public class JobCollectionDtoV2
{
[Required]
[FromRoute]
[RegularExpression("^[a-z][a-z0-9]+$")]
[StringLength(maximumLength: 24, MinimumLength = 3)]
public string Collection { get; set; }
[Required]
[FromRoute]
[RegularExpression("^[a-z][a-z0-9]+$")]
[StringLength(maximumLength: 24, MinimumLength = 3)]
public string Tenant { get; set; }
[Required]
[FromBody]
public JobCollectionDetails CollectionDetails { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
public class JobCollectionDetails
{
[Required]
public bool Enabled { get; set; }
[Required]
[CollectionFrequency]
public TimeSpan Frequency { get; set; }
}
上面的代码使NSwag生成以下Swagger文件:
{
"put": {
"tags": [
"JobCollectionsControllerV2"
],
"operationId": "JobCollectionsControllerV2_CreateTask",
"parameters": [
{
"type": "string",
"name": "collection",
"in": "path",
"required": true,
"maxLength": 24,
"minLength": 3,
"pattern": "^[a-z][a-z0-9]+$",
"x-nullable": false
},
{
"type": "string",
"name": "tenant",
"in": "path",
"required": true,
"maxLength": 24,
"minLength": 3,
"pattern": "^[a-z][a-z0-9]+$",
"x-nullable": false
},
{
"type": "object",
"name": "collectionDetails",
"in": "query",
"required": true,
"x-schema": {
"$ref": "#/definitions/JobCollectionDetails"
},
"x-nullable": true
}
],
"responses": {
"200": {
"x-nullable": true,
"description": "",
"schema": {
"$ref": "#/definitions/JobCollectionDtoV2"
}
}
}
}
}
看起来不错,以下部分除外,该部分指定collectionDetails
应该来自查询参数,而不是来自正文。
{
"type": "object",
"name": "collectionDetails",
"in": "query", <<<<-------------- SHOULD BE 'body' or something like that
"required": true,
"x-schema": {
"$ref": "#/definitions/JobCollectionDetails"
},
"x-nullable": true
}
我不确定如何解决此问题-非常感谢您对此提供的帮助。
谢谢!
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
services.AddMvc();
services.AddSwaggerDocument();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
_loggerFactory.AddDebug();
app.UseDeveloperExceptionPage();
app.UseSwagger(settings =>
{
settings.PostProcess = (document, request) =>
{
document.Info.Version = _context.CodePackageActivationContext.CodePackageVersion;
document.Info.TermsOfService = "None";
document.Info.Contact = new SwaggerContact
{
};
};
});
app.UseSwaggerUi3();
}
}
答案 0 :(得分:3)
我已将NSwag库更新到最新的v12(从v11版本开始),问题已解决-query
实际上已由body
取代
没有其他更改。