IT 공유기
.NET Core + SQL Server CRUD REST API 구현하기 본문
.net Core 초기 설정
NuGet 패키지 관리를 통하여서 아래의 패키지를 설치한다.
Microsoft.AspNetCore.Mvc.NewtonsoftJson
Microsoft.AspNetCore.Razor.Design
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Analyzers
Microsoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
System.Data.SqlClient
설치 후
---------------------------------------------
startup.cs에서 굵게 적힌 소스를 넣는다. JSON 직렬화 및 CORS 설정을 해줍니다.
(저도 CORS에 대해서 제대로 파악하지 못했습니다..)
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//Enable CORS 추가
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
//JSON Serializer 추가
services.AddControllersWithViews().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
= new DefaultContractResolver());
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//Enable CORS 추가
app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
---------------------------------------------
appsettings.json에서 sql 정보를 입력한다.
"ConnectionStrings": {
"StrCon": "Data Source=서버IP;Initial Catalog=DB명;User ID=DB ID;Password=DB PW;Connection Timeout=15"
},
서버IP/DB명/DB ID/DB PW는 본인 SQL 세팅상태에 맞게 입력해주세요.
이러면 어느정도 환경정보는 세팅이 완료가 됩니다.
---------------------------------------------
이전에 REST API의 구성요소에 대해서 간단히 적겠습니다.
Rest Api의 구성요소
1. HTTP Method
- GET 데이터 조회
- POST 데이터 추가
- PUT 데이터 수정
- PATCH 데이터 일부수정
- DELETE 데이터 삭제
2. URL - 데이터 접근
3. Representation - 자원의 표현
---------------------------------------------
우선 sql을 매핑 클래스를 적습니다.
public class Example
{
public int Id { get; set; }
public string Name { get; set; }
}
---------------------------------------------
Example 이란 테이블을 SQL에서 생성했습니다.
Create Table EXAMPLE(
[ID] int identity(1,1) primary key,
[NAME] varchar(200)
)
---------------------------------------------
저는 ValuesController라는 이름으로 Controller를 생성해서 밑과 같은 코드를 입력하였습니다.
//[Route("api/[controller]")]
[Route("api/values")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IConfiguration _configuration;
public ValuesController(IConfiguration configuration)
{
_configuration = configuration;
}
Rest api 구성요소
- GET 데이터 조회
해당 데이터가 조회 되는지 확인하기 위해서는 실행 후 controller에 맞는 URL을 바로 입력하여 들어간다.
들어가면 JSON 형식으로 데이터가 조회가 된다.
[HttpGet]
public JsonResult Get()
{
string query = @"
select Id, Name from
dbo.EXAMPLE
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("StrCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult(table);
}
Rest api 구성요소
- POST 데이터 추가
해당 소스가 실행되는지 확인하기 위해서는 POSTMAN을 씁니다.
참고로 POSTMAN web으로는 LOCAL 형태의 웹으로 들어올 수 없다.
그래서 Desktop버전으로 다운 받은 후 실행하면 다음과 같이 성공한다.
[HttpPost]
public JsonResult Post(Example exam)
{
string query = @"
insert into dbo.EXAMPLE([NAME])
values (@Name)
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("StrCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("@Name", exam.Name);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Added Successfully");
}
Rest api 구성요소
- PUT 데이터 수정
PUT은 데이터 전체 수정이다.
public JsonResult Put(Example exam)
{
string query = @"
update dbo.EXAMPLE
set Name= @Name
where Id=@Id
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("StrCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("@Id", exam.Id);
myCommand.Parameters.AddWithValue("@Name", exam.Name);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Updated Successfully");
}
Rest api 구성요소
- DELETE 데이터 삭제
[HttpDelete("{id}")]
public JsonResult Delete(int id)
{
string query = @"
delete from dbo.EXAMPLE
where Id=@Id
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("StrCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("@Id", id);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Deleted Successfully");
}
}
'C#' 카테고리의 다른 글
[C#] .net core appsetting.json 으로 값 들고오기 (0) | 2022.02.18 |
---|---|
c# POST방식으로 JSON data를 보내서 RESULT값 받는 법 (0) | 2021.09.15 |