中按项目分组Swagger,网络核心

ndh0cuux  于 2023-04-30  发布在  其他
关注(0)|答案(2)|浏览(106)

我正在做一个我称之为“主项目”的项目。我至少有10个不同的小项目在那里,这个项目可能会增长。我对所有这些项目都有一个 Swagger 的地方,因为所有这些项目都只使用一个dotnet核心web应用程序来进行泛化。
例如,假设我有一个名为SchoolJob的项目和一个名为HospitalJob的项目。SchoolJob有三个不同的端点,分别命名为GetStudentsTakeStudentsGetPaymentHostpitalJob有两个端点,分别命名为GetDoctorsGetNurses。这两个不同的项目将在一个swagger UI中看到:

- ../schooljob/getstudents
 - ../schooljob/takestudents 
 - ../schooljob/getpayment
 - ../hospitaljob/getdoctors
 - ../hospitaljob/getnurses

我想做的是在一个dotnet核心web项目中设置多个不同的swagger页面,或者对一个swagger进行分组,以便在不同的页面/或同一页面上看到它们,但不是同一时间。
../mainproject/swagger1/index.html或mainproject/swagger/schooljob UI应该是这样的:

- ../schooljob/getstudents
 - ../schooljob/takestudents 
 - ../schooljob/getpayment

../mainproject/swagger2/index.html或mainproject/swagger/hospitaljobUI应该是这样的

- ../hospitaljob/getdoctors
 - ../hospitaljob/getnurses
// Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    c.SwaggerDoc("schooljob", new OpenApiInfo
    {
        Version = "schooljob",
        Title = "School Job"
    });
    c.SwaggerDoc("hospitaljob", new OpenApiInfo
    {
        Version = "hospitaljob",
        Title = "Hospital Job"
    });
    // c.AddSecurityDefinition... and other swagger configurations
}   
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
    app.UseSwagger(c =>
    {
        c.RouteTemplate = "mainproject/swagger/{documentname}/swagger.json";
    });
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/mainproject/swagger/schooljob/swagger.json", "School Job");
        c.SwaggerEndpoint("/mainproject/swagger/hospitaljob/swagger.json", "Hospital Job");
        c.RoutePrefix = "mainproject/swagger";
        /c second prefix how?
    });
}
// SchoolController.cs

[HttpPost("schooljob/getstudents")]
[ApiExplorerSettings(GroupName = "schooljob")]
public JsonResult GetStudents([FromBody]OnaySayfasiId onaySayfasi)
{ ... }
// HospitalController.cs

[HttpPost("hospitaljob/getdoctors")]
[ApiExplorerSettings(GroupName = "hospitaljob")]
public JsonResult GetDoctors([FromBody]OnaySayfasiId onaySayfasi)
{ ... }

顺便说一下,我尝试使用API版本分组,但我再次看到所有这些端点。有什么方法可以做到这一点吗?

2ic8powd

2ic8powd1#

我知道你错过了什么,你使用了错误的控制器属性,这里你可以做什么:

  • 在控制器中,您必须使用[ApiVersion]而不是[ApiExplorerSettings(GroupName = ...)]属性。组是不同的,我猜它们是关于分组端点在Swagger页面的同一部分下。
  • 当一个方法参数需要一个版本时,请保持一致。OpenApiInfoSwaggerEndpointApiVersion需要相同的字符串,例如schooljob而不是School Job

我想如果你像下面这样更新你的代码,它应该可以工作:

// Startup.cs

app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/mainproject/swagger/schooljob/swagger.json", "schooljob");
        c.SwaggerEndpoint("/mainproject/swagger/hospitaljob/swagger.json", "hospitaljob");
        c.RoutePrefix = "mainproject/swagger";
        // No need for 2nd route prefix as there is only one Swagger page,
        // the content of the page gets updated when selecting a different version in the combobox.
    });

/* This line may be required in ConfigureServices method, give it a try */
/* services.AddApiVersioning(); */
// SchoolController.cs

[HttpPost("schooljob/getstudents")]
[ApiVersion("schooljob")]
public JsonResult GetStudents([FromBody]OnaySayfasiId onaySayfasi)
{ ... }

希望它能解决你的问题!

dwbf0jvd

dwbf0jvd2#

在程序中使用下面的代码。cs(.net 6),如果您正在使用。net 5(或更低版本)在strartup中使用此代码。CS

services.AddVersionedApiExplorer(options =>
    {
        options.GroupNameFormat = "'v'VV";
        options.SubstituteApiVersionInUrl = true;
    });

services.AddSwaggerGen(options =>
        {

            options.DocInclusionPredicate((documentName, apiDescription) =>
            {
                var actionApiVersionModel = apiDescription.ActionDescriptor.GetApiVersionModel();
                var apiExplorerSettingsAttribute = (ApiExplorerSettingsAttribute)apiDescription.ActionDescriptor.EndpointMetadata.First(x => x.GetType().Equals(typeof(ApiExplorerSettingsAttribute)));
                if (actionApiVersionModel == null)
                {
                    return true;
                }
                if (actionApiVersionModel.DeclaredApiVersions.Any())
                {
                    return actionApiVersionModel.DeclaredApiVersions.Any(v =>
                    $"{apiExplorerSettingsAttribute.GroupName}v{v}" == documentName);
                }
                return actionApiVersionModel.ImplementedApiVersions.Any(v =>
                       $"{apiExplorerSettingsAttribute.GroupName}v{v}" == documentName);
            });

            var apiVersionDescriptionProvider = services.BuildServiceProvider().GetService<IApiVersionDescriptionProvider>();
            foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
            {
                options.SwaggerDoc($"Orders{description.GroupName}", new OpenApiInfo
                {
                    Title = "Example Service",
                    Description = "Example Service -- Backend Service Project",
                    Version = description.ApiVersion.ToString(),
                    
                });
                options.SwaggerDoc($"Payments{description.GroupName}", new OpenApiInfo
                {
                    Title = "Example Service",
                    Description = "Example Service -- Backend Service Project",
                    Version = description.ApiVersion.ToString(),
                });
                // Orders & Payments are the groupName above ex: out put will be : swagger/OrdersV1.0/swagger.json ( if you select Orders from the swagger definition dropdown) 
                // If you select Payments => output : swagger/PaymentsV1.0/swagger.json
            }
            
            
var app = builder.Build();
                
            app.UseSwagger();

            app.UseSwaggerUI(
            swaggerOptions =>
            {                   
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    swaggerOptions.SwaggerEndpoint($"{swagger/Orders{description.GroupName}/swagger.json",$"Orders  {description.GroupName.ToUpperInvariant()}" );
                    swaggerOptions.SwaggerEndpoint($"{swagger/Payments{description.GroupName}/swagger.json", $"Payments  {description.GroupName.ToUpperInvariant()}");
                }
            });

控制器//V1 //示例控制器1:

[ApiVersion("1.0")]
[ApiController]
[ApiExplorerSettings(GroupName = "Orders")]
[Route("api/v{version:apiVersion}/[controller]")]
public class OrdersController : ControllerBase

//示例控制器2:

[ApiVersion("1.0")]
[ApiController]
[ApiExplorerSettings(GroupName = "Payments")]
[Route("api/v{version:apiVersion}/[controller]")]
public class PaymentsController : ControllerBase

相关问题