【发布时间】:2020-04-10 06:30:35
【问题描述】:
所以我使用 API 设置了一个新的解决方案。正如您在以下邮递员请求中所见,此 API 正在按预期工作:
{
"Id": 1,
"Name": "Samsung"
}
Swagger 生成这段代码:
{
"id": 0,
"name": "string"
}
此代码 sn-ps 显示了我的模型中的品牌。
如何修复它,以便 Swagger 采用第一个代码 sn-p 中所示的属性名称?
这就是我配置 API 和模型的方式:
配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
});
services.AddDbContext<PhoneCalculatorContext>(options => options.UseSqlServer(
Configuration["ConnectionStrings:DefaultConnection"]));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}
配置:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c => c.SerializeAsV2 = true);
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
型号:
public class Brand
{
public int Id { get; set; }
public string Name { get; set; }
}
【问题讨论】:
-
是小写吗?这是 dotnet 现在的默认设置,以符合其余标准
-
你能添加一张 swagger 显示的地方吗:
-
@saj 我不知道以小写形式编写给定数据是 REST 标准,因此我想整个问题是无关紧要的,我应该只使用小写字母?
-
如果我的回答有帮助,你能accept as answer吗?
标签: asp.net-core swagger asp.net-core-webapi ef-core-2.0