액션 메서드에서 Request 정보를 받아서 처리하는 방법을 알아보자.
Query Parameter 처리
query parameter를 액션 메서드에 바인딩 하는 방법은 파라미터를 추가하면 된다.
이전 글에서 생성했던, Hello 메서드를 보자.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ServerStudy.Controllers
{
[ApiController]
[Route("[Controller]")]
public class HomeController : ControllerBase
{
[Route("")]
[HttpGet]
public string Index()
{
return "HELLO WORLD!";
}
[Route("hello")]
[HttpGet]
public string Hello(string name)
{
return $"HELLO {name}";
}
}
}
Hello 액션 메서드를 살펴보면, name 파라미터가 추가되었다.
이제 이전 글에 수정했던 .http 파일에서
GET {{host}}/Home/hello?name=Lee
와 같이 요청하면

이렇게 응답을 받을 수 있다.
만약, 파라미터를 넣어주지 않으면

와 같이 파라미터가 없다는 결과를 받는다.
따라서 필수 파라미터가 아니라면 nullable 타입으로 넣어주면 된다.
[Route("hello")]
[HttpGet]
public string Hello(string? name)
{
return $"HELLO {name}";
}
Path Parameter 받기
path parameter는 url 내부에 포함된 파라미터 형태를 말한다.
url 내에 {}로 감싼 식별자를 넣어주고, 그 이름으로 파라미터에 바인딩 하면 된다.
[Route("hello/{name}")]
[HttpGet]
public string Hello(string? name)
{
return $"HELLO {name}";
}
이건, 테스트가 잘 안된다... 뭐가 문제인지 찾아봐야될듯..
Body Parameter 받기
bodystring 전체를 받으려면 파라미터에 [FromBody] 속성을 붙여주면 된다.
[Route("hello")]
[HttpGet]
public string Hello([FromBody] string? name)
{
return $"HELLO {name}";
}
이렇게 사용할 일은 많지 않을것이다.
Restful 에서는 기본적으로 데이터를 Json으로 주고받기 때문이다.
json 역직렬화를 편하게 하려면 DTO 타입을 정의해서 쓰는게 좋다.
public struct CreateProductRequestDTO
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
이런식으로 각 필드를 프로퍼티로 정의한다.
[Route("hello")]
[HttpPost]
[Consumes("application/json")]
public string Hello([FromBody] CreateProductRequestDTO dto)
{
return $"HELLO {dto.Id}, {dto.Name}, {dto.Price}";
}
이런식으로 받아서 처리하면 된다.
그리고, .http에서 이렇게 수정하자.
###
POST {{host}}/Home/hello
Content-Type: application/json
{
"id": 1,
"name": "Mouse",
"price": 10000
}
Get 에서 Post로 변경하였고, Body를 전달하고 있다.
이때, Body를 전달하는 중괄호 {} 는 꼭 한줄 띄워야한다.
Body 파라미터는 optional 설정이 기본이다.
전달되지 않아도 에러를 던지지 않는다.
그래서 필수 파라미터로 설정하려면
public struct CreateProductRequestDTO
{
[Required] public int Id { get; set; }
[Required] public string Name { get; set; }
[Required] public double Price { get; set; }
}
이렇게 [Required]를 설정해주면 된다.
근데 또, 숫자 타입은 필수로 전달 안해도 에러를 던지지 않는다...
POST {{host}}/Home/hello
Content-Type: application/json
{
"id": 1,
"name": "Mouse"
}
일때
HTTP/1.1 200 OK
Connection: close
Content-Type: text/plain; charset=utf-8
Date: Wed, 03 Dec 2025 08:13:21 GMT
Server: Kestrel
Transfer-Encoding: chunked
HELLO 1, Mouse, 0
=============================================
POST {{host}}/Home/hello
Content-Type: application/json
{
"id": 1,
"price": 10000
}
일때
HTTP/1.1 400 Bad Request
Connection: close
Content-Type: application/problem+json; charset=utf-8
Date: Wed, 03 Dec 2025 08:13:34 GMT
Server: Kestrel
Transfer-Encoding: chunked
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Name": [
"The Name field is required."
]
},
"traceId": "00-3e54589e731937547011543beb7eb48d-0cd40823cf17720f-00"
}
Header 값 읽어오기
헤더 값을 필요에 따라 직접 가져와서 처리하고 싶을 수 있다.
그럴때는 FromHeader 속성을 사용해서 파라미터에 바인딩을 하면 된다.
[Route("hello")]
[HttpPost]
public string Hello(
[FromHeader(Name = "user-agent")] string userAgent,
[FromBody] CreateProductRequestDTO dto)
{
return $"{userAgent}: {dto.Id}, {dto.Name}, {dto.Price}";
}
이런식으로 하고,
###
POST {{host}}/Home/hello
Content-Type: application/json
User-Agent: test
{
"id": 1,
"name": "Mouse",
"price": 10000
}
결과
HTTP/1.1 200 OK
Connection: close
Content-Type: text/plain; charset=utf-8
Date: Wed, 03 Dec 2025 08:21:38 GMT
Server: Kestrel
Transfer-Encoding: chunked
test: 1, Mouse, 10000
정상적으로 출력된다
만약 안되면, dotnet watch를 실행시킨 터미널을 ctrl + R 을 눌러서 새로 고침 해주자.
[HttpGet] 과 [HttpPost]
코드에서 HttpGet과 HttpPost가 등장했는데, 어떤 차이인지 잘 몰랐다.
간단하게 데이터를 읽기만하면 Get, 서버 상태를 바꾸면 Post다.
[HttpGet]
서버의 데이터/상태를 바꾸지 않고, 정보를 읽기만 하는 요청에 사용
예) 목록 조회, 상세 조회, 검색 등
URL 예:
GET /products
GET /products/10
GET /weatherforecast?date=2025-12-31
[HttpPost]
서버에 새 데이터를 만들거나 무언가 행위를 실행해서 상태를 바꾸는 요청에 사용함.
예) 회원 가입, 글 작성, 주문 생성, 결제 요청 등
URL 예:
POST /product (상품 생성)
POST /orders (주문 생성)
POST /users/login (로그인 시도)
그래서 위 코드에서도 JsonBody로 무언가 요청 객체를 보낼 경우엔 Post를 사용했다.
'Study > GameServer' 카테고리의 다른 글
| [ASP.NET Core] 05. 의존성 주입 방법의 라이프 사이클 (0) | 2025.12.04 |
|---|---|
| [ASP.NET Core] 04. 미들웨어와 파이프라인 (0) | 2025.12.04 |
| [ASP.NET Core] 03. Respose 처리 (0) | 2025.12.04 |
| [ASP.NET Core] 01. 컨트롤러와 Route 규칙 (0) | 2025.12.03 |
| [ASP.NET Core] 00. VSCode 환경설정 (Cursor포함) (0) | 2025.12.03 |