Today
-
Yesterday
-
Total
-

ABOUT ME

-

방문자

  • [ASP.Net Core API] Startup.cs에서 설정해야 할 것들 ( Swagger, CORS, formatFilter({format?}) )
    Microsoft .NET/ASP.Net & ASP.Net Core 2020. 11. 10. 10:51

    nuget에서 Swashbuckle.AspNetCore 설치

     

    빌드 일시 기록 버전

    더보기

    1. 프로젝트 파일 *.csproj를 메모장으로 열기

    2. AssemblyVersion를 1.0.*로 변경

    3. Deterministic를 false로 추가 등록

     

        <AssemblyVersion>1.0.*</AssemblyVersion>
        <Deterministic>false</Deterministic>

    public class Startup
    {
        #region CORS / Version -> DateTime
        readonly string MyAllowSpecificOrigins = "CORS";
    
        /// <summary>버전 정보를 넣으면 빌드 시간을 반환.</summary>
        public System.DateTime Get_BuildDateTime(System.Version version = null)
        {
            // 주.부.빌드.수정
            // 주 버전    Major Number
            // 부 버전    Minor Number
            // 빌드 번호  Build Number
            // 수정 버전  Revision NUmber
    
            //매개 변수가 존재할 경우
            if (version == null)
                version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
    
            //세번째 값(Build Number)은 2000년 1월 1일부터
            //Build된 날짜까지의 총 일(Days) 수 이다.
            int day = version.Build;
            System.DateTime dtBuild = (new System.DateTime(2000, 1, 1)).AddDays(day);
    
            //네번째 값(Revision NUmber)은 자정으로부터 Build된
            //시간까지의 지나간 초(Second) 값 이다.
            int intSeconds = version.Revision;
            intSeconds = intSeconds * 2;
            dtBuild = dtBuild.AddSeconds(intSeconds);
    
    
            //시차 보정
            System.Globalization.DaylightTime daylingTime = System.TimeZone.CurrentTimeZone
                    .GetDaylightChanges(dtBuild.Year);
            if (System.TimeZone.IsDaylightSavingTime(dtBuild, daylingTime))
                dtBuild = dtBuild.Add(daylingTime.Delta);
    
            return dtBuild;
        }
        #endregion
    
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
    
            #region IP
            services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
            #endregion
                
            #region FormatFilter (XML / JSON)
            services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; })
                                    .AddXmlSerializerFormatters()
                                    .AddXmlDataContractSeria‌​lizerFormatters();
            #endregion
    
            #region Create Swagger Document
            //스웨거 문서정보 생성.
            services.AddSwaggerGen(o =>
            {
                o.SwaggerDoc("v1"
                    , new Microsoft.OpenApi.Models.OpenApiInfo()
                    {
                        Title = "Sample API",
                        Description = "Sample API",
                        Version = "V1",
                        License = new Microsoft.OpenApi.Models.OpenApiLicense()
                        {
                            Name = "my Sample",
                            Url = new Uri("http://sample.co.kr")
                        }
                    });
                //애플리케이션의 기본 경로 (프로젝트-빌드-출력-XML 문서 파일 체크박스(TRUE))
                var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";    
                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
                //xml 경로
                o.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
            });
            #endregion
    
            #region CORS
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins()
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
            #endregion
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            #region Swagger UI
            //스웨거 미들웨어 설정
            app.UseSwagger();
    
            //스웨거 UI 활성화
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Version - "+ Get_BuildDateTime(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version).ToString("yyyy.MM.dd(ddd) tt hh:mm (zzz)"));
    
                //접속 경로 / 미입력 시 swagger
                //c.RoutePrefix = "swagger";
            });
            #endregion
    
            #region CORS
            app.UseCors(MyAllowSpecificOrigins);
            #endregion
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }

     

    일반

    더보기
    public class Startup
    {
        #region CORS
        readonly string MyAllowSpecificOrigins = "CORS";
        #endregion
    
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
    
            #region IP
            services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
            #endregion
                
            #region FormatFilter (XML / JSON)
            services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; })
                                    .AddXmlSerializerFormatters()
                                    .AddXmlDataContractSeria‌​lizerFormatters();
            #endregion
    
            #region Create Swagger Document
            //스웨거 문서정보 생성.
            services.AddSwaggerGen(o =>
            {
                o.SwaggerDoc("v1"
                    , new Microsoft.OpenApi.Models.OpenApiInfo()
                    {
                        Title = "Sample API",
                        Description = "Sample API",
                        Version = "V1",
                        License = new Microsoft.OpenApi.Models.OpenApiLicense()
                        {
                            Name = "my Sample",
                            Url = new Uri("http://sample.co.kr")
                        }
                    });
                //애플리케이션의 기본 경로 (프로젝트-빌드-출력-XML 문서 파일 체크박스(TRUE))
                var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";    
                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
                //xml 경로
                o.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
            });
            #endregion
    
            #region CORS
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins()
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
            #endregion
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            #region Swagger UI
            //스웨거 미들웨어 설정
            app.UseSwagger();
    
            //스웨거 UI 활성화
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    
                //접속 경로 / 미입력 시 swagger
                //c.RoutePrefix = "swagger";
            });
            #endregion
    
            #region CORS
            app.UseCors(MyAllowSpecificOrigins);
            #endregion
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
Posted by virtualgiraffe.