C# .NET

.NET Rest API

하농이 2023. 1. 17. 20:55

팀프로젝트 진행에 있어서 필요한 .NET을 활용하여 API를 구축하는 것에 대해 다룹니다.

 

🟪 테스트 버전 정보


  • .NET Framework 6.0
  • Visual Studio 2022

 

1. 프로젝트 생성

ASP.NET Croe 웹앱 선택

2. 컨트롤러 생성

MVC 컨트롤러 선택

3. Nuget Package 설치

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Swashbuckle.AspNetCore
  • Swashbuckle.AspNetCore.Annotations
  • Dapper
    • Dapper 란?
      • Dapper는 NET 프레임워크를 위한 마이크로소프트의 ORM(Object-Relational Mapping) 제품이다.
      • 개체 지향 도메인 모델을 기존 관계형 데이터베이스에 매핑하기 위한 프레임워크를 제공한다.
    **ORM(**Object Relational Mapping) 객체-관계 매핑의 줄임말이다. 객체-관계 매핑을 풀어서 설명하자면 우리가 OOP(Object Oriented Programming)에서 쓰이는 객체라는 개념을 구현한 클래스와 RDB(Relational DataBase)에서 쓰이는 데이터인 테이블 자동 으로 매핑(연결)하는 것을 의미한다. 그러나 클래스와 테이블은 서로가 기존부터 호환가능성을 두고 만들어진 것이 아니기 때문에 불일치가 발생하는데, 이를 ORM을 통해 객체 간의 관계를 바탕으로 SQL문을 자동으로 생성하여 불일치를 해결한다. 따라서 ORM을 이용하면 따로 SQL문을 짤 필요없이 객체를 통해 간접적으로 데이터베이스를 조작할 수 있게 된다.

4. Swagger 사용을 위한 설정

  • Rest API 를 curl, postman이 아닌 Swagger를 통해 테스트 하고자 한다.
  • Program.cs

  • 4번 줄

builder.Services.AddControllers() .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer();

  • 추가

builder.Services.AddSwaggerGen();

  • 14~15번줄

app.UseSwagger(); app.UseSwaggerUI();

  • launchSetting.json

  • ip와 포트번호만 입력해도 자동으로 swagger가 열리도록 설정

"launchBrowser": true, "launchUrl": "swagger",

 

5. 컨트롤러 작성

보통 클래스 위에 [Route(”v1/member”)] 처럼 api 버전과 구분할 수 있는 분야(?)를 적어준다. 그 후 클래스 안에 GET,POST,PUT,DELETE를 작성 할때에 Route를 다시 정의해주면 api를 호출할 때 ex) localhost:7572/v1/member/test 이렇게 호출이 가능하다.

 


참고

https://github.com/CodeMazeBlog/dapper-aspnetcore-webapi/tree/main/DapperASPNetCore/DapperASPNetCore

 

GitHub - CodeMazeBlog/dapper-aspnetcore-webapi: This repo contains the source code for the "Using Dapper with ASP.NET Core Web A

This repo contains the source code for the "Using Dapper with ASP.NET Core Web API" article on Code Maze - GitHub - CodeMazeBlog/dapper-aspnetcore-webapi: This repo contains the source co...

github.com

https://code-maze.com/using-dapper-with-asp-net-core-web-api/

 

Using Dapper with ASP.NET Core Web API - Code Maze

Let's learn how to use Dapper in ASP.NET Core Web API by using different querys, executions, transactions and repository pattern.

code-maze.com