.NET 6 Core API의 사용자 정의 특성

· 3분 읽기

사용자 정의 특성은 정말 사용하기 좋은 것입니다. 최근에 사용하기 시작했습니다. 그 중 하나를 만들고 컨트롤러, 클래스 또는 메서드 자체에서 재사용할 수 있기 때문입니다.

헤더 확인과 같은 일부 보안 작업을 수행하거나 반드시 필요한 매개변수 값을 확인하려는 경우 정말 도움이 됩니다.

제 경우에는 .NET Core API 프로젝트에서 이를 사용하여 모든 요청에 ​​특정 헤더가 포함되어 있는지 확인하겠습니다.

HeaderCheck속성

멋진 .NET Core API를 만든 후에는 폴더 사용을 좋아하므로 항목을 저장할 폴더를 만들어 보겠습니다.

그런 다음 HeaderCheckAttribute 클래스에 논리를 추가하겠습니다.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DotNet6CustomAttribute.Attributes
{
    public class HeaderCheckAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // Get all headers
            var headers = context.HttpContext.Request.Headers;

            // Check if headers has x-dotnet-6-custom-attribute
            if (!headers.ContainsKey("x-dotnet-6-custom-attribute"))
            {
                context.Result = new BadRequestObjectResult("The header x-dotnet-6-custom-attribute is missing");
            }
            else if (string.IsNullOrEmpty(headers["x-dotnet-6-custom-attribute"]))
            {
                context.Result = new BadRequestObjectResult("The header x-dotnet-6-custom-attribute can't be null or empty");
            }

            base.OnActionExecuting(context);
        }
    }
}

기본적으로 논리는 먼저 x-dotnet-6-custom-attribute 키가 있는 헤더를 확인하고 헤더가 있으면 값이 있는지 확인하는 것입니다.

두 표현식이 모두 true이면 특정 메시지와 함께 BadRequestObjectResult를 다시 반환합니다.

컨트롤러에 추가하기

이 로직을 여러 위치에 추가할 수 있고, 전체 컨트롤러에 직접 추가할 수도 있고, 일부 메서드에 추가할 수도 있습니다. 먼저 메서드에 추가한 다음 전체 컨트롤러에 추가하겠습니다.

그럼 WeatherForecastController 클래스를 그것들로 장식해 봅시다.

using DotNet6CustomAttribute.Attributes;
using Microsoft.AspNetCore.Mvc;

namespace DotNet6CustomAttribute.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [Route("GetWeatherForecastWithCheck")]
        [HeaderCheckAttribute]
        public IEnumerable<WeatherForecast> GetWithCheck()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet]
        [Route("GetWeatherForecastWithoutCheck")]
        public IEnumerable<WeatherForecast> GetWithoutCheck()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

프로젝트를 실행해보자!

여기에는 GetWeatherForecastWithCheckGetWeatherForecastWithoutCheck라는 두 가지 기능이 있습니다. 그 중 하나는 실패하고 다른 하나는 실패하지만 Swagger에서 확인해 보겠습니다!

그 중 하나는 메시지와 함께 400 오류를 반환하고 다른 하나는 값을 반환하는 것을 볼 수 있듯이 이제 이를 완전히 테스트하기 위해 Postman을 실행하고 헤더를 추가하여 GetWeatherForecastWithCheck를 사용하여 데이터도 볼 수 있도록 하겠습니다.

우편배달부

이제 Postman에서 실행하면서 헤더를 추가하고 오류 메시지가 변경된 것을 확인합니다. 이제 헤더를 제공하지만 값이 없기 때문입니다.

여기에 값을 추가하면 마침내 값을 얻게 됩니다!

그게 다야

그게 다야! 아주 간단하죠? 이제 속성을 생성하고 이를 메서드와 컨트롤러에 할당하는 방법을 알았습니다!

그들과 함께 즐거운 시간을 보내세요!

코드

이 전체 프로젝트는 Github에 있으며 여기에서 찾을 수 있습니다!

문제나 질문이 있는 경우 소셜 미디어 @emimontesdeoca로 언제든지 저에게 연락해 주세요(트위터에서는 실제로 @emimontesdeocaa이고 끝에 두 개의 aa가 있습니다). 블로그 헤더에서 내 소셜 미디어의 대부분을 찾을 수도 있습니다.

게시물이 마음에 드셨기를 바랍니다! 시아!