.net 增加 Swagger 解决跨域

一、swagger使用

1.打开Nuget,搜索安装Swashbuckle.AspNetCore。

2.生成api文档

 3.Program.cs 添加如下代码 FreightForwarderApi.xml  替换成你的。

var basePath = AppContext.BaseDirectory;





builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "Api"
    });

    var xmlPath = Path.Combine(basePath, "FreightForwarderApi.xml");
    c.IncludeXmlComments(xmlPath, true);
    //var xmlDomainPath = Path.Combine(basePath, "NET6.Domain.xml");
    //c.IncludeXmlComments(xmlDomainPath, true);
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "Value: Bearer {token}",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
    {
      {
        new OpenApiSecurityScheme
        {
          Reference = new OpenApiReference
          {
            Type = ReferenceType.SecurityScheme,
            Id = "Bearer"
          },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
        },new List<string>()
      }
    });
});
Program文件增加

4.运行后就有了

5.新增控制器,增加接口显示。增加基类

6.其他控制器,基于该类

运行如下:

 参照:https://blog.csdn.net/mengke2815/article/details/122408876?spm=1001.2014.3001.5502

二、如下创建startup.cs 

1.修改Program.cs 

namespace FreightForwarderApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
全部代码

2.新增文件:Startup.cs  包含解决跨域。

using log4net;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.OpenApi.Models;
using System.Text;

namespace FreightForwarderApi
{
    public class Startup
    {
        // 该方法用来添加服务到容器
        public void ConfigureServices(IServiceCollection services)
        {
            // 添加跨域资源共享(CORS)支持   
            services.AddCors(options => options.AddPolicy("CorsPolicy",
               builder =>
               {
                   builder.AllowAnyMethod()
                       .SetIsOriginAllowed(_ => true)
                       .AllowAnyHeader()
                       .AllowCredentials();
               }));

            var basePath = AppContext.BaseDirectory;
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie();
            services.AddControllersWithViews();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Api"
                });
                var xmlPath = Path.Combine(basePath, "FreightForwarderApi.xml");
                c.IncludeXmlComments(xmlPath, true);
                //var xmlDomainPath = Path.Combine(basePath, "NET6.Domain.xml");
                //c.IncludeXmlComments(xmlDomainPath, true);
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "Value: Bearer {token}",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                  {
                    new OpenApiSecurityScheme
                    {
                      Reference = new OpenApiReference
                      {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                      },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
                    },new List<string>()
                  }
                });
            });

            //跨域
            services.AddCors();


        }

        // 该方法用来配置HTTP请求管道
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (!env.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCors("CorsPolicy");

            var appsettings = new ConfigurationBuilder()
                             .SetBasePath(Environment.CurrentDirectory)
                             .AddJsonFile("appsettings.json", true, true)
                             .Build();

            var varCorsUrls = appsettings.GetSection("CorsUrls").Value;

            app.UseCors(builder =>
            {
                builder.WithOrigins(varCorsUrls.Split(',')).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });

            #region 启用swaggerUI
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
                c.RoutePrefix = string.Empty;
                c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
                c.DefaultModelsExpandDepth(-1);
            });

            #endregion
            app.UseRouting();

            app.UseCors(cfg =>
            {
                cfg.AllowAnyOrigin();
                cfg.AllowAnyMethod();
                cfg.AllowAnyHeader();
            });
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
            });        
        }
    }
}
全部代码

 

posted @ 2024-05-17 16:45  丁焕轩  阅读(14)  评论(0编辑  收藏  举报