AutoMapper에서 해시드를 사용하는 방법
해시드를 사용하는 이유는 무엇입니까?
Hashids은 숫자 Id를 문자열로 변환하는 데 도움이 됩니다. 이렇게 하면 API에서 데이터를 요청할 때 DB의 실제 ID 또는 관련 키를 숨겨서 앱을 좀 더 안전하게 만들 수 있습니다.
AutoMapper의 ValueConverter가 왜 유용한가요?
ValueConverter은 te
.Map<TDestination>(source) 메서드 내에서 변환을 처리할 수 있으므로 변환 논리를 한 곳에만 배치할 수 있습니다.모델
//Model of your data
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ClassEnrollmentId { get; set; }
}
//Data Transfer Object (DTO) for your client
public class StudentDto
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string ClassEnrollmentId { get; set; }
}
구성
너겟 패키지를 설치한 후:
Install-Package hashids.net Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection Program.cs에 다음 코드를 추가하여 종속성 주입과 함께 해시 및 AutoMapper를 사용합니다. Startup 클래스를 사용하려면 ConfigureServices 메서드에 넣어야 합니다.
builder.Services.AddSingleton<IHashids>(_ => 
new Hashids("this is my salt"));
// Optional, you can set the length of the string 
// new Hashids("this is my salt", [the number you want])
builder.Services.AddAutoMapper(typeof(AutoMapperProfile));
AutoMapper 프로필
using AutoMapper; // To use the Profile class
public class AutoMapperProfile: Profile
{
    public AutoMapperProfile()
    {
        //This configuration convert the int property who saves Ids to hash string
        CreateMap<Student, StudentDto>()
            .ForMember(d => d.Id, opt => opt.ConvertUsing<HashFormatter, int>())
            .ForMember(d => d.ClassEnrollmentId, opt => opt.ConvertUsing<HashFormatter, int>());
        //This configuration makes the oposite from the above configuration
        CreateMap<StudentDto, Student>()
            .ForMember(d => d.Id, opt => opt.ConvertUsing<IntFromHash, string>())
            .ForMember(d => d.ClassEnrollmentId, opt => opt.ConvertUsing<IntFromHash, string>());
    }
}
변환 클래스
using AutoMapper; //To use IValueConverter interface
using HashidsNet; //To use IHashids interface
public class HashFormatter : IValueConverter<int, string>
{
    private readonly IHashids hashids;
    public HashFormatter(IHashids hashids)
    {
        this.hashids = hashids;
    }
    public string Convert(int source, ResolutionContext context)
    {
        return hashids.Encode(source);
    }
}
public class IntFromHash : IValueConverter<string, int>
{
    private readonly IHashids hashids;
    public IntFromHash(IHashids hashids)
    {
        this.hashids = hashids;
    }
    public int Convert(string source, ResolutionContext context)
    {
        return hashids.DecodeSingle(source);
    }
}
사용 방법
컨트롤러에서는 AutoMapper를 주입하고 이와 같이
.Map 메서드를 호출하기만 하면 됩니다.public class StudentstController : ControllerBase
{
    private readonly IMapper mapper;
    public StudentstController(IMapper mapper)
    {
        this.mapper = mapper;
    }
    [HttpGet]
    public IActionResult Get()
    {
        //Summaries is the data as List<Student>
        return Ok(mapper.Map<List<StudentDto>>(Summaries));
    }
}
결과
해시가 없는 데이터
[
  {
    "id": 1,
    "name": "Juan",
    "classEnrollmentId": 2
  },
  {
    "id": 2,
    "name": "Pedro",
    "classEnrollmentId": 1
  }
]
해시가 있는 데이터
[
  {
    "id": "NV",
    "name": "Juan",
    "classEnrollmentId": "6m"
  },
  {
    "id": "6m",
    "name": "Pedro",
    "classEnrollmentId": "NV"
  }
]
이 글을 읽어주셔서 감사합니다. 도움이 되었으면 합니다.
Reference
이 문제에 관하여(AutoMapper에서 해시드를 사용하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/luisnogal/value-converter-of-automapper-for-hashids-4h6p텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)