Asp.net-Core
Swagger UI 顯示 camelCase 參數而不是 PascalCase
我在 Asp.Net Core 3.1 API 中使用 NewtonSoft.json 和 Swashbuckle.AspNetCore 版本 5.3.3。
預設情況下,在 Asp.Net Web API 中,2 個輸入和輸出參數大小寫為 PascalCase。
現在我正在遷移到預設情況下為 camelCase 的 .Net Core API。
所以我通過在 Startup.cs 中添加以下程式碼將其更改為使用 PascalCase:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; }) .AddNewtonsoftJson(options => { // Use the default property (Pascal) casing options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });//Configure Newtonsoft as JSON serializer.但在 Swagger UI 中,它以 camelCase 格式顯示輸入和輸出參數,而 API 的響應包含 PascalCase 格式的值。
我用Google搜尋,但在 AddSwaggerGen DescribeAllParametersInCamelCase() 中找到了一個方法,它將所有參數轉換為 camelCase。
有 DescribeAllParametersInPascalCase() 方法嗎?
如何配置 Swagger/Swashbuckle 以在 PascalCase 中顯示輸入/輸出參數?
這是一個例子:
您可以像這樣配置 JsonSerializerOptions:
.AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null)
如果您仍在使用
Newtonsoft.JsonAsp.Net Core 3.1 而不是新的 defualtSystem.Text.Json。為 Asp.Net Core 3.1 配置 Newtonsoft 後:
services.AddControllers().AddNewtonsoftJson(x => { // My config is Pascal Case x.SerializerSettings.ContractResolver = new DefaultContractResolver(); });您還需要
Swashbuckle.AspNetCore.Newtonsoft通過在之後添加以下內容來安裝並選擇加入services.AddSwaggerGen(...:services.AddSwaggerGenNewtonsoftSupport();
