如何在 ASP.NET Boilerplate Web API 中进行版本控制? [英] How to do versioning in ASP.NET Boilerplate Web API?

查看:21
本文介绍了如何在 ASP.NET Boilerplate Web API 中进行版本控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ASP.NET Boilerplate 框架中进行版本控制.

我在 Swagger Gen 中创建了两个版本(v1.0"和v2.0")并为 Web API 设置了 API 版本,但每次我都从 Swagger 获取两个版本中的所有 API.

Startup.cs:

AddSwaggerGenConfigureServices() 中:

services.AddSwaggerGen(options =>{options.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });options.SwaggerDoc("v2.0", new Info { Title = "My API", Version = "v2.0" });options.DocInclusionPredicate((docName, description) => true);//定义正在使用的 BearerAuth 方案options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme(){Description = "JWT Authorization header using the Bearer scheme. Example: "Authorization: Bearer {token}"",Name = "授权",在 =标题"中,类型 = "apiKey"});//根据 AuthorizeAttribute 为操作分配范围要求options.OperationFilter();});

UseSwaggerUI 在 Configure() 中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){app.UseAbp(options => { options.UseAbpRequestLocalization = false; });app.UseCors(_defaultCorsPolicyName);app.UseStaticFiles();app.UseAuthentication();app.UseAbpRequestLocalization();app.UseSignalR(routes =>{route.MapHub("/signalr");});app.UseMvc(routes =>{路线.MapRoute(name: "defaultWithArea",模板:{area}/{controller=Home}/{action=Index}/{id?}");路线.MapRoute(名称:默认",模板:{controller=Home}/{action=Index}/{id?}");});app.UseSwagger();app.UseSwaggerUI(options =>{options.InjectOnCompleteJavaScript("/swagger/ui/abp.js");options.InjectOnCompleteJavaScript("/swagger/ui/on-complete.js");options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "我的 API V1.0");options.SwaggerEndpoint("/swagger/v2.0/swagger.json", "我的 API V2.0");});}

API 控制器 - v1.0:

[ApiVersion("v1.0")][路由(/api/invoicemodule/1.0/[控制器]")]公共类 InvoiceController : MyControllerBase{[HttpGet, MapToApiVersion("v1.0")]公共 IActionResult GetInvoiceById(string invoiceid){//BusinessService.SparePartHistoryService sas = new BusinessService.SparePartHistoryService(_logger, _localizer, _configuration);if (string.IsNullOrEmpty(invoiceid)) return BadRequest("'Id'不能为空或空.");尝试{BusinessModels.Invoice sp = 新的 BusinessModels.Invoice{编号 = ""};如果(sp != 空){返回 Ok(sp);}别的{返回 NotFound();}}捕获(例外 e){返回 BadRequest(e.Message);}}}

API 控制器 - v2.0:

[ApiVersion("v2.0")][路由(/api/invoicemodule/2.0/[控制器]")]公共类 InvoiceController : MyControllerBase{[HttpGet, MapToApiVersion("v2.0")]公共 IActionResult GetInvoiceById(string invoiceid){//BusinessService.SparePartHistoryService sas = new BusinessService.SparePartHistoryService(_logger, _localizer, _configuration);if (string.IsNullOrEmpty(invoiceid)) return BadRequest("'Id'不能为空或空.");尝试{BusinessModels.Invoice sp = 新的 BusinessModels.Invoice{编号 = ""};如果(sp != 空){返回 Ok(sp);}别的{返回 NotFound();}}捕获(例外 e){返回 BadRequest(e.Message);}}}

输出

解决方案

是的,我找到了解决方案

参考:https://github.com/domaindrivendev/Swashbuckle.AspNetCore >

我在 Startup.cs 文件的 ConfigurationService() 方法中更改了 Service.AddSwaggerGen() 的少量代码

在我更改的代码中添加的注释

 services.AddSwaggerGen(options =>{options.SwaggerDoc("v1", new Info { Version = "1" });//版本必须是整数.无法设置版本 = "v1"options.SwaggerDoc("v2", new Info { Version = "2" });options.DocInclusionPredicate((docName, description) =>{//插入此 {} 代码而不是true"var 版本 = description.ControllerAttributes().OfType().SelectMany(attr => attr.Versions);return versions.Any(v => $"v{v.ToString()}" == docName);});});

I am trying to do versioning in ASP.NET Boilerplate framework.

I have created two versions in Swagger Gen ("v1.0" and "v2.0") and set API version for Web API, but every time I get all API in both versions from Swagger.

Startup.cs:

AddSwaggerGen in ConfigureServices():

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });
    options.SwaggerDoc("v2.0", new Info { Title = "My API", Version = "v2.0" });
    options.DocInclusionPredicate((docName, description) => true);

    // Define the BearerAuth scheme that's in use
    options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: "Authorization: Bearer {token}"",
        Name = "Authorization",
        In = "header",
        Type = "apiKey"
    });
    // Assign scope requirements to operations based on AuthorizeAttribute
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

UseSwaggerUI in Configure():

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); 

    app.UseCors(_defaultCorsPolicyName); 

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseAbpRequestLocalization();

    app.UseSignalR(routes =>
    {
        routes.MapHub<AbpCommonHub>("/signalr");
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "defaultWithArea",
            template: "{area}/{controller=Home}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.UseSwagger();

    app.UseSwaggerUI(options =>
    {
        options.InjectOnCompleteJavaScript("/swagger/ui/abp.js");
        options.InjectOnCompleteJavaScript("/swagger/ui/on-complete.js");
        options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My API V1.0");
        options.SwaggerEndpoint("/swagger/v2.0/swagger.json", "My API V2.0");
    }); 
}

API Controller - v1.0:

[ApiVersion("v1.0")]
[Route("/api/invoicemodule/1.0/[controller]")]
public class InvoiceController : MyControllerBase
{       
    [HttpGet, MapToApiVersion("v1.0")]
    public IActionResult GetInvoiceById(string invoiceid)
    {
        //BusinessService.SparePartHistoryService sas = new BusinessService.SparePartHistoryService(_logger, _localizer, _configuration);

        if (string.IsNullOrEmpty(invoiceid)) return BadRequest("'Id' cannot be null or empty.");

        try
        {
            BusinessModels.Invoice sp = new BusinessModels.Invoice
            {
                Id = ""
            };
            if (sp != null)
            {
                return Ok(sp);
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }
}

API Controller - v2.0:

[ApiVersion("v2.0")]
[Route("/api/invoicemodule/2.0/[controller]")]
public class InvoiceController : MyControllerBase
{
    [HttpGet, MapToApiVersion("v2.0")]
    public IActionResult GetInvoiceById(string invoiceid)
    {
        //BusinessService.SparePartHistoryService sas = new BusinessService.SparePartHistoryService(_logger, _localizer, _configuration);

        if (string.IsNullOrEmpty(invoiceid)) return BadRequest("'Id' cannot be null or empty.");

        try
        {
            BusinessModels.Invoice sp = new BusinessModels.Invoice
            {
                Id = ""
            };
            if (sp != null)
            {
                return Ok(sp);
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }
}

Output

解决方案

Yeah, I got the solution

Reference : https://github.com/domaindrivendev/Swashbuckle.AspNetCore

I have changed little code of Service.AddSwaggerGen() in ConfigurationService() method of Startup.cs file

Comments added in code where i have changed

      services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new Info { Version = "1" }); // Version must require in integer. can't set Version = "v1"
            options.SwaggerDoc("v2", new Info { Version = "2" });
            options.DocInclusionPredicate((docName, description) =>
            { // insert this {} code instead of "true" 
                var versions = description.ControllerAttributes()
                .OfType<ApiVersionAttribute>()
                .SelectMany(attr => attr.Versions);

                return versions.Any(v => $"v{v.ToString()}" == docName);
            });
        });

这篇关于如何在 ASP.NET Boilerplate Web API 中进行版本控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆