Action 메서드에서 응답을 제어하는 방법을 알아보자.
JSON Response 처리
ASP.NET Core에서 별 다른 설정 없이 객체를 반환하면, JSON으로 자동 변환되어 쏴준다.
조건이 조금 있는데
public struct CreateProductRequestDTO
{
[Required] public int Id { get; set; }
[Required] public string Name { get; set; }
[Required] public double Price { get; set; }
}
이전 글에서 썼던 코드다.
여기에서 보이듯, 각 필드가 대문자로 시작해야 하고, get/set 프로퍼티여야 한다.
[Route("hello")]
[HttpGet]
public CreateProductRequestDTO Hello([FromBody] CreateProductRequestDTO dto)
{
var response = new CreateProductRequestDTO();
response.Id = dto.Id;
response.Name = dto.Name;
response.Price = dto.Price;
return response;
}
그리고 그냥 리턴해주면 된다.
###
GET {{host}}/Home/hello
Content-Type: application/json
{
"id": 1,
"name": "Mouse",
"price": 10000
}
결과
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json; charset=utf-8
Date: Thu, 04 Dec 2025 01:12:12 GMT
Server: Kestrel
Transfer-Encoding: chunked
{
"id": 1,
"name": "Mouse",
"price": 10000
}
정상적으로 json을 리턴하는걸 볼 수 있다.
비동기 핸들링 : Task
ASP.NET은 Task기반의 async/await 기능을 기본 지원한다.
[Route("hello")]
[HttpGet]
public async Task<CreateProductRequestDTO> Hello([FromBody] CreateProductRequestDTO dto)
{
var response = new CreateProductRequestDTO();
response.Id = dto.Id;
response.Name = dto.Name;
response.Price = dto.Price;
await Task.Delay(1000); // 1초 대기
return response;
}
async 를 달고, Task 값을 리턴한다고 해준 후, await를 사용하면 된다.
가변 리턴타입: IActionResult, ActionResult<T>
IActionResult는 여러가지 리턴 타입을 포괄해 사용할 수 있는, 일종의 래퍼 타입이다.
상태 코드 조작이나, 이런 저런 커스텀 응답이 필요할 때 이걸 쓴다.
IActionResult (기본형)
반환 타입이 명확하지 않거나, 여러 종류의 응답을 반환할 때 사용한다.
ex) OK(), BadRequest(), NotFound(), Created() 등
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
if (id <= 0)
return BadRequest("Invalid ID"); // 400 Bad Request
var product = GetProductById(id);
if (product == null)
return NotFound(); // 404 Not Found
return Ok(product); // 200 OK with product
}
유연하다는 장점이 있지만, 타입 안정성이 낮다는 단점이 있다.
ActionResult<T> (제네릭타입)
반환 타입이 명확할 때 사용한다.
T는 성공 시 반환할 데이터 타입이다.
성공시 T를 반환하고, 실패시 IActionResult계열(BadRequest, NotFound 등)도 반환 가능하다.
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
if (id <= 0)
return BadRequest("Invalid ID"); // 400 Bad Request
var product = GetProductById(id);
if (product == null)
return NotFound(); // 404 Not Found
return product; // 200 OK - 자동으로 Ok(product)로 변환됨
// 또는 명시적으로: return Ok(product);
}
상태 코드 조작
상태 코드(202, 200 등)를 임의로 변경해서 쓸때가 종종 있다.
그럴땐, 응답을 StatusCode로 감싸서 반환하면 된다.
[Route("hello")]
[HttpGet]
public IActionResult Hello([FromBody] CreateProductRequestDTO dto)
{
var response = new CreateProductRequestDTO();
response.Id = dto.Id;
response.Name = dto.Name;
response.Price = dto.Price;
return StatusCode(202, response);
}
###
GET {{host}}/Home/hello
Content-Type: application/json
{
"id": 1,
"name": "Mouse",
"price": 10000
}
응답
HTTP/1.1 202 Accepted //202로 반환됨.
Connection: close
Content-Type: application/json; charset=utf-8
Date: Thu, 04 Dec 2025 01:57:57 GMT
Server: Kestrel
Transfer-Encoding: chunked
{
"id": 1,
"name": "Mouse",
"price": 10000
}
리다이렉트
리다이렉트란, "이 URL 말고, 저 URL로 가세요" 라고 서버가 클라이언트에게 알려주는 동작이다.
1. 클라이언트가 A URL로 요청
2. 서버가 "A 말고 B로 가세요" 라고 응답
3. 클라이언트가 자동으로 다시 B로 요청
==============================
실제 예시 (http -> https 리다이렉트)
1. 사용자가 입력 (http://example.com/login)
2. 서버 응답 "307 Temporary Redirect -> https://example.com/login"
3. 브라우저가 자동으로 https://example.com/login 으로 다시 요청
리다이렉트는 Controller 상위 클래스에 있는 Redirect 함수를 사용하면 된다.
[Route("hello")]
[HttpGet]
public IActionResult Hello([FromBody] CreateProductRequestDTO dto)
{
var response = new CreateProductRequestDTO();
response.Id = dto.Id;
response.Name = dto.Name;
response.Price = dto.Price;
return Redirect("https://freeedeveloper.tistory.com/");
}'Study > GameServer' 카테고리의 다른 글
| [ASP.NET Core] 05. 의존성 주입 방법의 라이프 사이클 (0) | 2025.12.04 |
|---|---|
| [ASP.NET Core] 04. 미들웨어와 파이프라인 (0) | 2025.12.04 |
| [ASP.NET Core] 02. Request 처리 (0) | 2025.12.03 |
| [ASP.NET Core] 01. 컨트롤러와 Route 규칙 (0) | 2025.12.03 |
| [ASP.NET Core] 00. VSCode 환경설정 (Cursor포함) (0) | 2025.12.03 |