asp.net mvc에서 controller로 들어오는 파라미터 종류(정리중입니다.)
안녕하세요.
이번에는 asp.net MVC controller에서 사용하는 파라미터에 대해 정리해보겠습니다.
1. 경로 (Route) 파라미터
경로 파라미터는 URL 경로의 일부로 전달되는 값입니다. 주로 라우팅 규칙을 통해 전달됩니다.
예를 들면 아래 Route 규칙에 따라 URL: /products/details/5 에서 5는 id값이 되겠습니다.
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
public class ProductsController : Controller { public IActionResult Details(int id) { return View(); } }
2. 쿼리 문자열 (Query String) 파라미터
쿼리 문자열 파라미터는 URL의 쿼리 부분에 포함되는 값입니다. 일반적으로 URL의 ?
뒤에 이어지는 이름-값 쌍으로 전달됩니다.
/products/search?name=laptop&category=electronics 와 같이 쿼리문자열로 넘어오는 방법입니다.
public class ProductsController : Controller { public IActionResult Search(string name, string category) { return View(); } }
3. 폼 데이터 (Form Data)
폼 데이터는 HTML 폼을 통해 POST 요청으로 전달되는 값입니다. 이는 주로 사용자 입력 데이터를 서버로 전송할 때 사용됩니다.
public class ProductsController : Controller { [HttpPost] public IActionResult Create(ProductModel model) { return View(); } }
<form method="post" action="/products/create"> <input type="text" name="Name" /> <input type="number" name="Price" /> <button type="submit">Create</button> </form>
4. 본문 (Body) 데이터
본문 데이터는 HTTP 요청의 본문에 포함되는 데이터입니다. 주로 JSON이나 XML 형식으로 전달되며, Web API에서 주로 사용됩니다.
public class ProductsController : Controller { [HttpPost] public IActionResult Create([FromBody] ProductModel model) { return View(); } }
5. 헤더 (Header) 데이터
헤더 데이터는 HTTP 요청의 헤더 부분에 포함되는 값입니다. 인증 토큰이나 사용자 에이전트와 같은 메타데이터가 여기에 포함됩니다.
public class ProductsController : Controller { public IActionResult GetProduct() { var userAgent = Request.Headers["User-Agent"].ToString(); return View(); } }