{"id":90074,"date":"2023-06-03T08:12:47","date_gmt":"2023-06-03T06:12:47","guid":{"rendered":"https:\/\/code-maze.com\/?p=90074"},"modified":"2024-04-04T17:52:41","modified_gmt":"2024-04-04T15:52:41","slug":"aspnetcore-pass-parameters-to-http-get-action","status":"publish","type":"post","link":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/","title":{"rendered":"How to Pass Parameters With a GET Request in ASP.NET Core"},"content":{"rendered":"<p>In this article, we&#8217;ll discuss the different ways to pass parameters to a <code>GET<\/code> request in ASP.NET Core.<\/p>\n<div style=\"padding: 20px; border-left: 5px color:#dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for the video, visit our <a href=\"https:\/\/www.patreon.com\/posts\/source-code-ways-99785963?src=passParamsGetRequest\" target=\"_blank\" rel=\"nofollow noopener\">Patreon page<\/a> (YouTube Patron tier).<\/div>\n<p>Before we dive into this topic, we recommend going through the basics of <a href=\"https:\/\/code-maze.com\/net-core-web-development-part5\/\" target=\"_blank\" rel=\"noopener\">handling the GET request<\/a> and <a href=\"https:\/\/code-maze.com\/aspnetcore-webapi-best-practices\/\" target=\"_blank\" rel=\"noopener\">best practices for ASP.NET Core Web API<\/a>.<\/p>\n<p>When working with ASP.NET Core, we use <code>GET<\/code> methods to retrieve data from a web API. We often must pass parameters to a <code>GET<\/code> method to specify which data to retrieve.<\/p>\n<p>There are several ways we can pass parameters to a method:<\/p>\n<ul>\n<li>Query parameters<\/li>\n<li>Route parameters<\/li>\n<li>Combination of query and route parameters<\/li>\n<li>Request body<\/li>\n<li>Header Parameters<\/li>\n<\/ul>\n<p>Let&#8217;s take a closer look at each section to gain a better understanding.<\/p>\n<hr \/>\r\n<p style=\"text-align: center;\"><strong>VIDEO<\/strong>: Pass Parameters With a GET Request in ASP.NET Core.<\/p>\r\n<p style=\"text-align: center;\"><iframe width=\"560\" height=\"315\" src=https:\/\/www.youtube.com\/embed\/mcvF6sxiuvg?si=7KY1Ol9j6l-uQVzr frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/p>\r\n<hr \/>\n<h2>Setting Up the Application<\/h2>\n<p>To start with, we&#8217;ll create two model classes, <code>Product<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Product\r\n{\r\n    public int Id { get; set; }\r\n    public string? Category { get; set; }\r\n    public string? Brand { get; set; }\r\n    public string? Name { get; set; }\r\n    public int WarrantyYears { get; set; }\r\n    public bool IsAvailable { get; set; }\r\n}<\/pre>\n<p>And <code>ProductDto<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class ProductDto\r\n{\r\n    public int Id { get; set; }\r\n    public string? Category { get; set; }\r\n    public string? Brand { get; set; }\r\n    public string? Name { get; set; }\r\n    public int WarrantyYears { get; set; }\r\n    public bool IsAvailable { get; set; }\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">Then, we will create a <\/span><code>Map<\/code> <span style=\"font-weight: 400;\">class to map the data from the <\/span><code>Product<\/code> <span style=\"font-weight: 400;\">class to the <\/span><code>ProductDto<\/code> <span style=\"font-weight: 400;\">class:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Map : Profile\r\n{\r\n    public Map()\r\n    {\r\n        CreateMap&lt;Product, ProductDto&gt;();\r\n    }\r\n}<\/pre>\n<p>To better understand how AutoMapper works, we suggest reading our guide on using <a href=\"https:\/\/code-maze.com\/automapper-net-core\/\" target=\"_blank\" rel=\"noopener\">AutoMapper in ASP.NET Core<\/a>.<\/p>\n<p>Now, let&#8217;s create a <code>ProductController<\/code> class and define a list of\u00a0products:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[ApiController]\r\n[Route(\"api\/[controller]\")]\r\npublic class ProductController : ControllerBase\r\n{\r\n    private readonly List&lt;Product&gt; _products = new()\r\n    {\r\n        new Product{ Id = 1, Category = \"Electronic\", Brand = \"Sony\", \r\n                     Name = \"Play Station\", WarrantyYears = 2, IsAvailable = true },\r\n        \/\/removed other entires for a better readability\r\n        new Product{ Id = 7, Category = \"Electronic\", Brand = \"Apple\", \r\n                     Name = \"Mobile\", WarrantyYears = 2, IsAvailable = true }\r\n    };\r\n}<\/pre>\n<p>Finally, let&#8217;s declare a\u00a0field named <code>mapper<\/code> of type <code>IMapper<\/code>, and inject an instance of <code>IMapper<\/code> in the constructor:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private readonly IMapper _mapper;\r\n\r\npublic ProductController(IMapper mapper)\r\n{\r\n    _mapper = mapper;\r\n}<\/pre>\n<p>Now that we have finished the initial steps, let&#8217;s explore each section in detail.<\/p>\n<h2>Query Parameters<\/h2>\n<p>In a <code>GET<\/code> method, we commonly use query strings to pass parameters. We include them in the URL as key-value pairs separated by an equal sign and separate multiple parameters by an ampersand symbol.<\/p>\n<p>Query parameters begin with a question mark (?), and we put them after the URL<span style=\"font-weight: 400;\">. If any route parameters exist in the URL, query parameters should be placed after them.<\/span><\/p>\n<p>In this URL, <code>category<\/code> and <code>brand<\/code> are the query parameters with the values &#8220;Electronic&#8221; and &#8220;Sony&#8221;:<\/p>\n<p><code>https:\/\/localhost:7097\/api\/Product?category=Electronic&amp;brand=Sony<\/code><\/p>\n<p><strong>When we work with query parameters, we have the option to use the <code>[FromQuery]<\/code> attribute to bind parameters from the query string explicitly. However, the parameter binding process automatically converts request data into strongly typed parameters. This process eliminates the need for explicit <code>[FromQuery]<\/code> attribute usage.<\/strong><\/p>\n<p>First, let&#8217;s create a GET method without using the <code>[FromQuery]<\/code> attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet]\r\npublic IActionResult GetProductsByCategoryAndBrand(string category, string brand)\r\n{\r\n    List&lt;Product&gt; result = _products\r\n        .Where(x =&gt; x.Category == category &amp;&amp; x.Brand == brand)\r\n        .ToList();\r\n\r\n    return Ok(_mapper.Map&lt;List&lt;ProductDto&gt;&gt;(result));\r\n}<\/pre>\n<p>We have a GET endpoint that accepts two parameters\u00a0<code>category<\/code> and <code>brand<\/code>. Then, we use the LINQ <code>Where<\/code> method to filter the <code>_products<\/code> based on the <code>category<\/code> and <code>brand<\/code> and map the result with the <code>ProductDto<\/code> class.<\/p>\n<p>Let&#8217;s proceed by sending a request to the endpoint:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPrams.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-90076 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPrams.png\" alt=\"Pass two query prameters with a Get request in Postman\" width=\"588\" height=\"683\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPrams.png 588w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPrams-258x300.png 258w\" sizes=\"auto, (max-width: 588px) 100vw, 588px\" \/><\/a><\/p>\n<p>We can observe that parameter names in our method signature align with the query parameter names in the request URL, so the framework automatically binds the values from the query string to the method parameters based on their names and filters the <code>_products<\/code>.<\/p>\n<p>Sometimes, we may encounter situations where the parameter names in the method signature do not match the query parameter names. In such scenarios, we can explicitly use the <code>[FromQuery]<\/code> attribute to bind the query parameters to the respective method parameters.<\/p>\n<p>Now, let&#8217;s create a <code>GET<\/code> method that takes two parameters from the query string, and we use the <code>FromQuery<\/code> attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"type-manufacturer\")]\r\npublic IActionResult GetProductsByCategoryAndBrandUsingFromQuery(\r\n    [FromQuery(Name = \"type\")] string category,\r\n    [FromQuery(Name = \"manufacturer\")] string brand)\r\n{\r\n    List&lt;Product&gt; result = _products\r\n        .Where(x =&gt; x.Category == category &amp;&amp; x.Brand == brand)\r\n        .ToList();\r\n\r\n    return Ok(_mapper.Map&lt;List&lt;ProductDto&gt;&gt;(result));\r\n}<\/pre>\n<p>We use <code>[FromQuery(Name = \"type\")]<\/code> and <code>[FromQuery(Name = \"manufacturer\")]<\/code> attribute to bind the values of query parameters <code>type<\/code> and <code>manufacturer<\/code> to the corresponding method parameters <code>category<\/code> and <code>brand<\/code>.<\/p>\n<p>To test this, let&#8217;s send a request with two query parameters:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPramsWithAttribute-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-90077\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPramsWithAttribute-1.png\" alt=\"Postman Result showing the API request and response.\" width=\"726\" height=\"683\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPramsWithAttribute-1.png 726w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryPramsWithAttribute-1-300x282.png 300w\" sizes=\"auto, (max-width: 726px) 100vw, 726px\" \/><\/a><\/p>\n<p>The API filters the data and returns the result based on the query parameters <code>type<\/code> and <code>manufacturer<\/code>.<\/p>\n<p><strong>Since there is a limit to the length of a URL, query parameters have a limited capacity for passing data. <\/strong>Check out this helpful <a href=\"https:\/\/stackoverflow.com\/questions\/812925\/what-is-the-maximum-possible-length-of-a-query-string#answer-812953\" target=\"_blank\" rel=\"nofollow noopener\">resource<\/a>\u00a0for information on the maximum character limit for a query string in <code>GET<\/code> requests for different browsers.<\/p>\n<p>Additionally, query parameters are not secure because the values are visible in the URL, making them vulnerable to interception by malicious users.\u00a0<\/p>\n<h2>Route Parameters<\/h2>\n<p><span style=\"font-weight: 400;\">We can also use route parameters to pass data but in a different way. <\/span>Route parameters are placeholders in the URL. <span style=\"font-weight: 400;\">We use route parameters to identify a specific resource or resources, while the query parameters to sort\/filter those resources.<\/span><\/p>\n<p>We recognize <span style=\"font-weight: 400;\">route parameters <\/span>by curly braces ({}) containing a parameter name as part of the route template.<\/p>\n<p>Let&#8217;s take a look at an URL that contains the route parameter:<\/p>\n<p><code>https:\/\/localhost:7097\/api\/Product\/2<\/code><\/p>\n<p>We use this URL to access a product resource by passing the product Id as a route parameter to the API endpoint.<\/p>\n<p><strong>By default, the framework binds route parameters based on their names when we use route parameters, allowing us to omit the <code>[FromRoute]<\/code> attribute. However, there are scenarios where the parameter names in the method signature differ from the route parameter names. In such situations, we can use the <code>[FromRoute]<\/code> attribute.<\/strong><\/p>\n<p>Let&#8217;s create another <code>GET<\/code> method without using <code>FromRoute<\/code> attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"{id}\")]\r\npublic IActionResult GetProductById(int id)\r\n{\r\n    return Ok(_mapper.Map&lt;ProductDto&gt;(_products\r\n        .Where(x =&gt; x.Id == id)\r\n        .FirstOrDefault()));\r\n}<\/pre>\n<p>Firstly, we define a <code>GET<\/code> method with a route parameter &#8220;id&#8221; using the <code>[HttpGet(\"{id}\")]<\/code> attribute. Then, using the LINQ query, we filter the <code>_products<\/code> and map the retrieved product to a <code>ProductDto<\/code>.<\/p>\n<p>Let&#8217;s send a request with a route parameter:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParams.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-90078 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParams.png\" alt=\"Pass route parameters with a Get request in Postman\" width=\"485\" height=\"340\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParams.png 485w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParams-300x210.png 300w\" sizes=\"auto, (max-width: 485px) 100vw, 485px\" \/><\/a><\/p>\n<p>The API utilizes the route parameter to identify the specific resource.<\/p>\n<p>Let&#8217;s create an additional <code>GET<\/code> method that uses <code>[FromRoute]<\/code> attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"productId\/{productId}\")]\r\npublic IActionResult GetProductByIdUsingFromRoute([FromRoute(Name = \"productId\")] int id)\r\n{\r\n    return Ok(_mapper.Map&lt;ProductDto&gt;(_products\r\n        .Where(x =&gt; x.Id == id)\r\n        .FirstOrDefault()));\r\n}<\/pre>\n<p>In this <code>GET<\/code> method, we define a <code><span class=\"hljs-params\">[FromRoute(Name = <span class=\"hljs-string\">\"productId\"<\/span><\/span>)]<\/code>\u00a0attribute to bind the <code>productId<\/code>\u00a0parameter to the corresponding action method parameter.<\/p>\n<p>Let&#8217;s send a request to the endpoint:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParamsWithAttribute-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-90079\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParamsWithAttribute-3.png\" alt=\"Postman Result showing the API request and response.\" width=\"482\" height=\"349\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParamsWithAttribute-3.png 482w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/RouteParamsWithAttribute-3-300x217.png 300w\" sizes=\"auto, (max-width: 482px) 100vw, 482px\" \/><\/a><\/p>\n<p>As we can see, API identifies the resource based on the route parameter we passed.<\/p>\n<h2>Combination of Query and Route Parameters<\/h2>\n<p><span style=\"font-weight: 400;\">We can combine query and route params to pass params in a <code>GET<\/code> method. <\/span>It is often more appropriate to pass a set of required parameters as route parameters and optional parameters as query parameters.<\/p>\n<p>With this approach, we can design an API endpoint to include some of the parameters in the URL as route parameters while passing others in the URL as query parameters. The route parameters help identify the requested primary resource, while the query parameters help filter the result based on additional criteria.<\/p>\n<p>Now, we&#8217;ll create a <code>GET<\/code> method that uses both query and route params::<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"brand\/{brand}\")]\r\npublic IActionResult GetProductsByBrandAndWarranty(string brand, int warranty)\r\n{\r\n    return Ok(_mapper.Map&lt;List&lt;ProductDto&gt;&gt;(_products\r\n        .Where(x =&gt; x.Brand == brand &amp;&amp; x.WarrantyYears == warranty)\r\n        .ToList()));\r\n}<\/pre>\n<p>The <code>brand<\/code> parameter is included in the URL as a route parameter while we pass the <code>warranty<\/code> as a query parameter. This allows retrieving <code>_products<\/code> by the <code>brand<\/code>\u00a0while further filtering the result by the <code>warranty<\/code>.<\/p>\n<p>We&#8217;ll send a request to the endpoint:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParams-1-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-90080\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParams-1-3.png\" alt=\"Postman Result showing the API request and response.\" width=\"523\" height=\"642\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParams-1-3.png 523w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParams-1-3-244x300.png 244w\" sizes=\"auto, (max-width: 523px) 100vw, 523px\" \/><\/a><\/p>\n<p>The API filters the <code>_products<\/code> based on the route and query parameters.<\/p>\n<p><span style=\"font-weight: 400;\">Now, let&#8217;s create a new <code>GET<\/code> action method that uses both the <code>[FromQuery]<\/code> and <code>[FromRoute]<\/code> attributes:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"manufacturer\/{manufacturer}\")]\r\npublic IActionResult GetProductsByBrandAndWarrantyUsingAttributes(\r\n    [FromRoute(Name = \"manufacturer\")] string brand,\r\n    [FromQuery(Name = \"coverage\")] int warranty)\r\n{\r\n    return Ok(_mapper.Map&lt;List&lt;ProductDto&gt;&gt;(_products\r\n        .Where(x =&gt; x.Brand == brand &amp;&amp; x.WarrantyYears == warranty)\r\n        .ToList()));\r\n}<\/pre>\n<p>We have a <code>GET<\/code> endpoint that retrieves products based on the brand and warranty attributes. We use the <code>[FromRoute(Name = \"manufacturer\")]<\/code> attribute\u00a0to ensure that the value for the <code>brand<\/code> parameter is retrieved from the route segment. Meanwhile, the <code>[FromQuery(Name = \"coverage\")]<\/code> attribute indicates that the <code>warranty<\/code> value will be obtained from the query string.<\/p>\n<p><span style=\"font-weight: 400;\">Let&#8217;s send a request:<\/span><\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParamsWithAttributes-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-90081 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParamsWithAttributes-2.png\" alt=\"Pass parameters with a Get request using Query and Route Parameters\" width=\"645\" height=\"649\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParamsWithAttributes-2.png 645w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParamsWithAttributes-2-298x300.png 298w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParamsWithAttributes-2-150x150.png 150w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/QueryRouteParamsWithAttributes-2-75x75.png 75w\" sizes=\"auto, (max-width: 645px) 100vw, 645px\" \/><\/a><\/p>\n<p>By utilizing both the <code>brand<\/code> route parameter and the <code>coverage<\/code> query parameter, the API filters the <code>_products<\/code>.<\/p>\n<h2>Request Body<\/h2>\n<p>We typically use the request body for more complex or sensitive data that we cannot easily pass in the URL. It is commonly used in HTTP <code>POST<\/code>, <code>PUT<\/code>, and <code>PATCH<\/code> methods to send data to the server. <strong>According to the<\/strong> <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Methods\/GET\" target=\"_blank\" rel=\"nofollow noopener\">best practices of REST API<\/a>, <strong>we don&#8217;t recommend passing parameters through the request body in a <code>GET<\/code> method, although it is possible.<\/strong><\/p>\n<p>We encapsulate the parameters in a model or class to use the request body to pass multiple parameters to a <code>GET<\/code> method. The properties of the model should correspond to the parameters we pass.<\/p>\n<p>By default, the HTTP methods <code>GET<\/code>, <code>HEAD<\/code>, <code>OPTIONS<\/code>, and <code>DELETE<\/code> do not bind data implicitly from the request body. To bind data explicitly from the request body, marked as JSON, for these methods, we can use the <code>[FromBody]<\/code> attribute. Also, we can use the <code>[FromQuery]<\/code> attribute as we did in our <a href=\"https:\/\/code-maze.com\/paging-aspnet-core-webapi\/\" target=\"_blank\" rel=\"noopener\">Pagination article<\/a>.<\/p>\n<p><span style=\"font-weight: 400;\">For this example, we are going to create another <code>GET<\/code> method that accepts the request body using <code>[FromBody]<\/code> attribute:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"category\")]\r\npublic IActionResult GetProductsByCategory([FromBody] ProductDto model)\r\n{\r\n    return Ok(_mapper.Map&lt;List&lt;ProductDto&gt;&gt;(_products\r\n        .Where(x =&gt; x.Category == model.Category)\r\n        .ToList()));\r\n}<\/pre>\n<p>We use the route name &#8220;category&#8221; to indicate that we want to retrieve a list of <code>_products<\/code> belonging to a specific category. We utilize the <code>ProductDto<\/code> class to pass the model into the request body. The <code>[FromBody]<\/code> attribute binds the request body values to the specified model.<\/p>\n<p>Furthermore, we use LINQ to filter the <code>_products<\/code> based on their category and map the resulting <code>_products<\/code> to the <code>ProductDto<\/code> class.<\/p>\n<p><strong>Passing data in a request body is more secure than exposing the values in the URL.<\/strong><\/p>\n<p><span style=\"font-weight: 400;\">Let&#8217;s send a request to the endpoint:<\/span><\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/FromBody.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-90082\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/FromBody.png\" alt=\"Postman Result showing the API request and response.\" width=\"435\" height=\"698\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/FromBody.png 435w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/FromBody-187x300.png 187w\" sizes=\"auto, (max-width: 435px) 100vw, 435px\" \/><\/a><\/p>\n<p>The API filters the result based on the <code>category<\/code> parameter passed in the request body in JSON format.<\/p>\n<h2>Header Parameters<\/h2>\n<p>Header parameters are another way to pass data to a <code>GET<\/code> method using <code>[FromHeader]<\/code> attribute. Unlike query and route parameters, header parameters are not part of the URL. Instead, we can send them as part of the request headers.<\/p>\n<p>Header parameters are an essential aspect of HTTP requests that provide additional information about the request. We can use header parameters to convey information such as authentication tokens, content type, and content-encoding.<\/p>\n<p>Now, we&#8217;ll create a <code>GET<\/code> method that uses the header parameters:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"category-brand\")]\r\npublic IActionResult GetProductsByCategoryAndBrandViaHeaders([FromHeader] string category, [FromHeader] string brand)\r\n{\r\n    return Ok(_mapper.Map&lt;List&lt;ProductDto&gt;&gt;(_products\r\n        .Where(x =&gt; x.Category == category &amp;&amp; x.Brand == brand)\r\n        .ToList()));\r\n}<\/pre>\n<p>We use the <code>[FromHeader]<\/code> attribute to bind the <code>category<\/code> and <code>brand<\/code> header parameter values to the corresponding method parameters. We use &#8220;category-brand&#8221; as the route name because it filters the <code>_products<\/code> based on the provided <code>category<\/code> and <code>brand<\/code>. Then using the header parameters, we filter the <code>_products<\/code> using the LINQ <code>Where()<\/code> method, map them to <code>ProductDto<\/code> and return them.<\/p>\n<p><span style=\"font-weight: 400;\">Using header parameters in GET requests is an excellent option to pass sensitive parameter values to avoid exposing them in the URL.<\/span><\/p>\n<p>Let&#8217;s go ahead and send a request <span style=\"font-weight: 400;\">using the header parameters<\/span>:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/HeaderParams-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-90083 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/HeaderParams-3.png\" alt=\"Postman Result when we pass parameters with a GET reqeust\" width=\"710\" height=\"656\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/HeaderParams-3.png 710w, https:\/\/code-maze.com\/wp-content\/uploads\/2023\/05\/HeaderParams-3-300x277.png 300w\" sizes=\"auto, (max-width: 710px) 100vw, 710px\" \/><\/a><\/p>\n<p>When we send the API request, we pass the <code>category<\/code> and <code>brand<\/code> parameters in the headers, which the API uses to filter the results and return the <code>_products<\/code>.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we discussed various ways of passing parameters to a <code>GET<\/code> method.<\/p>\n<p>We commonly use query and route parameters to pass parameters in <code>GET<\/code> requests. However, if the parameter values are sensitive, header parameters or the request body may be more appropriate. We recommend avoiding passing data in the request body for <code>GET<\/code> requests and only considering it if other options are not feasible.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;ll discuss the different ways to pass parameters to a GET request in ASP.NET Core. Before we dive into this topic, we recommend going through the basics of handling the GET request and best practices for ASP.NET Core Web API. When working with ASP.NET Core, we use GET methods to retrieve data [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62187,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[171],"tags":[79,586,1817,121,1816,14,544,290,1011,47,1815,130,45],"class_list":["post-90074","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-http","tag-asp-net-core","tag-asp-net-core-web-api","tag-body-request","tag-get","tag-header-parameters","tag-http","tag-linq","tag-parameters","tag-query-string-parameters","tag-rest-api","tag-route-parameters","tag-web-api","tag-web-development","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Pass Parameters With a GET Request in ASP.NET Core<\/title>\n<meta name=\"description\" content=\"This article will discuss ways to pass parameters with a GET request in ASP.NET Core, including query params, route params, body and headers.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Pass Parameters With a GET Request in ASP.NET Core\" \/>\n<meta property=\"og:description\" content=\"This article will discuss ways to pass parameters with a GET request in ASP.NET Core, including query params, route params, body and headers.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-03T06:12:47+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-04T15:52:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Pass Parameters With a GET Request in ASP.NET Core\",\"datePublished\":\"2023-06-03T06:12:47+00:00\",\"dateModified\":\"2024-04-04T15:52:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\"},\"wordCount\":1637,\"commentCount\":4,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"keywords\":[\"asp.net core\",\"asp.net core web api\",\"Body Request\",\"GET\",\"Header Parameters\",\"HTTP\",\"LINQ\",\"Parameters\",\"Query String Parameters\",\"REST API\",\"Route Parameters\",\"Web API\",\"web development\"],\"articleSection\":[\"HTTP\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\",\"url\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\",\"name\":\"How to Pass Parameters With a GET Request in ASP.NET Core\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"datePublished\":\"2023-06-03T06:12:47+00:00\",\"dateModified\":\"2024-04-04T15:52:41+00:00\",\"description\":\"This article will discuss ways to pass parameters with a GET request in ASP.NET Core, including query params, route params, body and headers.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"width\":1100,\"height\":620,\"caption\":\"ASP.NET Core\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Pass Parameters With a GET Request in ASP.NET Core\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Pass Parameters With a GET Request in ASP.NET Core","description":"This article will discuss ways to pass parameters with a GET request in ASP.NET Core, including query params, route params, body and headers.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/","og_locale":"en_US","og_type":"article","og_title":"How to Pass Parameters With a GET Request in ASP.NET Core","og_description":"This article will discuss ways to pass parameters with a GET request in ASP.NET Core, including query params, route params, body and headers.","og_url":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/","og_site_name":"Code Maze","article_published_time":"2023-06-03T06:12:47+00:00","article_modified_time":"2024-04-04T15:52:41+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Pass Parameters With a GET Request in ASP.NET Core","datePublished":"2023-06-03T06:12:47+00:00","dateModified":"2024-04-04T15:52:41+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/"},"wordCount":1637,"commentCount":4,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","keywords":["asp.net core","asp.net core web api","Body Request","GET","Header Parameters","HTTP","LINQ","Parameters","Query String Parameters","REST API","Route Parameters","Web API","web development"],"articleSection":["HTTP"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/","url":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/","name":"How to Pass Parameters With a GET Request in ASP.NET Core","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","datePublished":"2023-06-03T06:12:47+00:00","dateModified":"2024-04-04T15:52:41+00:00","description":"This article will discuss ways to pass parameters with a GET request in ASP.NET Core, including query params, route params, body and headers.","breadcrumb":{"@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","width":1100,"height":620,"caption":"ASP.NET Core"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/aspnetcore-pass-parameters-to-http-get-action\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Pass Parameters With a GET Request in ASP.NET Core"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/90074","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=90074"}],"version-history":[{"count":16,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/90074\/revisions"}],"predecessor-version":[{"id":104036,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/90074\/revisions\/104036"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62187"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=90074"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=90074"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=90074"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}