첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
다운로드

▶ CustomNameConstraint.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace TestProject
{
    /// <summary>
    /// 커스텀 명칭 제약 조건
    /// </summary>
    public class CustomNameConstraint : IRouteConstraint
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 정규식
        /// </summary>
        private Regex regex;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - CustomNameConstraint()

        /// <summary>
        /// 생성자
        /// </summary>
        public CustomNameConstraint()
        {
            this.regex = new Regex
            (
                @"^[1-9]*$",
                RegexOptions.CultureInvariant | RegexOptions.IgnoreCase,
                TimeSpan.FromMilliseconds(100)
            );
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 매칭 여부 구하기 - Match(httpContext, route, routeKey, valueDictionary, routeDirection)

        /// <summary>
        /// 매칭 여부 구하기
        /// </summary>
        /// <param name="httpContext">HTTP 컨텍스트</param>
        /// <param name="router">라우터</param>
        /// <param name="routeKey">경로 키</param>
        /// <param name="valueDictionary">경로 값 딕셔너리</param>
        /// <param name="routeDirection">경로 방향</param>
        /// <returns>매칭 여부</returns>
        public bool Match
        (
            HttpContext          httpContext,
            IRouter              router,
            string               routeKey,
            RouteValueDictionary valueDictionary,
            RouteDirection       routeDirection
        )
        {
            if(valueDictionary.TryGetValue(routeKey, out object value))
            {
                string parameterValue = Convert.ToString(value, CultureInfo.InvariantCulture);

                if(parameterValue == null)
                {
                    return false;
                }

                return regex.IsMatch(parameterValue);
            }

            return false;
        }

        #endregion
    }
}

 

728x90

 

▶ Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace TestProject
{
    /// <summary>
    /// 시작
    /// </summary>
    public class Startup
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 구성 - Configuration

        /// <summary>
        /// 구성
        /// </summary>
        public IConfiguration Configuration { get; }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - Startup(configuration)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="configuration">구성</param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 서비스 컬렉션 구성하기 - ConfigureServices(services)

        /// <summary>
        /// 서비스 컬렉션 구성하기
        /// </summary>
        /// <param name="services">서비스 컬렉션</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddRouting
            (
                options =>
                {
                    options.ConstraintMap.Add("customName", typeof(CustomNameConstraint));
                }
            );
        }

        #endregion
        #region 구성하기 - Configure(app, environment)

        /// <summary>
        /// 구성하기
        /// </summary>
        /// <param name="app">애플리케이션 빌더</param>
        /// <param name="environment">웹 호스트 환경</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
        {
            if(environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints
            (
                endpoints =>
                {
                    endpoints.MapControllers();
                }
            );
        }

        #endregion
    }
}

 

300x250

 

▶ Controllers/TestController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Docs.Samples;

namespace TestProject.Controllers
{
    /// <summary>
    /// 테스트 컨트롤러
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class TestController : ControllerBase
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        // GET /api/test/3
        #region 구하기 - Get(id)

        /// <summary>
        /// 구하기
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>액션 결과</returns>
        [HttpGet("{id:customName}")]
        public IActionResult Get(string id)
        {
            return ControllerContext.MyDisplayRouteInfo(id);
        }

        #endregion
        // GET /api/test/my/3
        #region 구하기 -  Get(id)

        /// <summary>
        /// 구하기
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>액션 결과</returns>
        [HttpGet("my/{id:customName}")]
        public IActionResult Get(int id)
        {
            return ControllerContext.MyDisplayRouteInfo(id);
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요