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

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

问题描述

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

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

Startup.cs :

中的

AddSwaggerGen:

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在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控制器-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控制器-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);
        }
    }
}

输出

解决方案

是的,我找到了解决方法

参考资料: https://github.com/domaindrivendev/Swashbuckle.AspNetCore

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

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

      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);
            });
        });

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天全站免登陆