카테고리 없음2020. 9. 17. 14:05

Web API 프로젝트에 Swagger 을 적용한 뒤에 Parameter 에 대한 설명등을 추가하려면 별도의 작업이 필요합니다.

이를 위해 XML 관련 설정을 추가해 주고 소스 코드에 주석을 달면

이를 자동화해서 도움말에 설명도 추가 할 수 있습니다.

Startup.cs 의 ConfiguraServices 메소드에 아래 내용을 적용 후

#region Locate the XML file being generated by ASP.NET...
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                //... and tell Swagger to use those XML comments.
                c.IncludeXmlComments(xmlPath);
                #endregion

Controller 구현부에 아래와 같은 ///주석을 통해 설명을 추가합니다.

        /// <summary>
        /// Create Templete
        /// </summary>
        /// <remarks>
        /// Request Body : {"uId":"아이디","charId":"캐릭터ID","name":"이름"}
        /// </remarks>
        /// <param name="uId">아이디</param>
        /// <param name="charId">캐릭터ID</param>
        /// <param name="name">이름</param>
        /// <returns>A serialized json string</returns>
        [HttpPost]
        [Produces("application/json")]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [Route("CreateTemplate")]
        public ActionResult CreateTemplate()
        {
            /// body
        }

소스 코드에 적용한 주석은 아래와 같은 형태로 설명 문서에 적용됩니다.

exceptionnotfound.net/adding-swagger-to-asp-net-core-web-api-using-xml-documentation/

Posted by 굥쓰
Study/ASP.NET MVC & Core2020. 9. 16. 14:33

API 구현 하면서 문서화에 대한 부분은 고민이 많은데 Swagger 를 적용하면 몇 라인의 코드 적용만으로도

문서화 및 디버깅까지 가능한 훌륭한 구조를 프로젝트에 포함 시킬 수 있는 장점이 있습니다.

 

1. 구현 미리보기

2. Nuget 패키지 관리에서 Swashbuckle.AspNetCore  추가

3. Startup.cs

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen(c => {

                // sepcify our operation filter here.  
                c.OperationFilter<AddCommonParameOperationFilter>();

                c.SwaggerDoc("api", new OpenApiInfo { Title = "Web API", Description = "WebAPI 사용법\r\nId : 43, charId : 282362182980730885"
                , Contact = new OpenApiContact { Name = "Minecraft", Email = string.Empty
                , Url = new Uri("http://localhost:1790") }
                });
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                app.UseSwagger();
                app.UseSwaggerUI(c => {
                    c.SwaggerEndpoint("api/swagger.json", "Api Documents");
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
        }

docs.microsoft.com/ko-kr/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-3.1

 

Swagger/OpenAPI를 사용한 ASP.NET Core Web API 도움말 페이지

이 자습서에서는 Swagger를 추가하여 Web API 앱에 대한 설명서 및 도움말 페이지를 생성하는 연습을 제공합니다.

docs.microsoft.com

 

4. 사용자 정의 Parameter 처리를 위한 클래스 추가

Web API 개발의 일반 적인 구조는 Entity 를 주고 받는 형태로 되어 있으므로 이 부분은 불필요 하지만

Entity 를 사용하지 않는 구조라면 고려할 만 합니다.

Custom 파라미터 적용을 위한 방법

https://www.c-sharpcorner.com/article/add-custom-parameters-in-swagger-using-asp-net-core-3-1/

 

Add Custom Parameters In Swagger Using ASP.NET Core 3.1

This article showed you a sample of how to add custom request parameters in Swagger using ASP.NET Core 3.1 and Swashbuckle.AspNetCore 5.0.0

www.c-sharpcorner.com

위 구조를 적용하고 나면 1번 미리보기 화면의 uId, charId 입력 파라미터 구조를 사용할 수 있습니다.

뚝딱뚝딱! MSDN 문서 뒤지고 구글링 해봐도 머리만 아팠는데 막상 적용하고 나니 깔끔하네요. ^ㅡ^

 

Posted by 굥쓰