.Net WebApi2从零开始

1、创建

  VS创建WebApi应用,模板选择空模板,核心应用选择Web Api,右键解决方案在生成中勾选生产Xml文件。

2、多版本配置

  路由中添加多个路由

  

 config.Routes.MapHttpRoute(
    name: "Apiv1",
    routeTemplate: "api/v1/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
    name: "Apiv2",
    routeTemplate: "api/v2/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

  创建两个版本的控制器

 注意每个方法都要加上Route,否则会出现V2请求到V1去。

3、配置Swaager

  Nuget安装Swashbuckle、Swagger.NET.UI然后App_Start文件夹中的SwaggerNet文件注释掉类上面的两个assembly,SwaggerConfig中做如下配置,

  

GlobalConfiguration.Configuration
                 .EnableSwagger(c =>
                 {
                    // c.SingleApiVersion("v1", "组织人事OpenApi");
                    c.MultipleApiVersions((q, e) => { return q.ActionDescriptor.ControllerDescriptor.ControllerType.FullName.ToLower().Contains(string.Format(".{0}.", e)); },
                        vc => { vc.Version("v1", "组织人事OpenApiV1"); vc.Version("v2", "组织人事OpenApiV2"); });
                    //// 配置接口不显示打过期标签的接口,一般开启该配置
                    //c.IgnoreObsoleteActions();
                    //// 配置Model中不显示打过期标签的属性,一般开启该配置
                    //c.IgnoreObsoleteProperties();
                    //// 配置授权方式,基于Tita的Token授权方式的可以完全Copy下面内容
                    //c.ApiKey("apiKey")
                    // .Description("API Key Authentication")
                    // .Name("Authorization")
                    // .In("header");
                   // c.DocumentFilter<ApplyDocumentVendorExtensions>();
                    // 如果存在接口使用其他项目下Model的,需要保证被使用项目生成了XML文件(下面使用TargetXML.xml表示),使用下面方式使Model也展示Model注释
                    c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}BinWebApplication1.xml");
                 }).EnableSwaggerUi(c => { });

  

原文地址:https://www.cnblogs.com/jfwangncs/p/15381044.html