[HttpGet] Not passing [FromBody]

Donald T. Hess 0 Reputation points
2023-04-21T15:06:28.39+00:00

Question Is there a way to force a GET to send a Body with standard ASP.NET MVC Controller We are using a standard Controller from Microsoft's MVC. If we try to do a HttpGet("api/inventory/search") with a [FromBody] The body contents will NOT be serialized into the data item.
I know the WWW standard is a bit loose on supporting Get's with Bodies. However the call contains some sensitive information and we do not want to pass it via [FromQuery]

[HttpGet("api/inventory")]
[Produces("application/json")]
public async Task<IActionResult> SearchInventory([FromHeader] string tenant, [FromBody] GetInventoryRequest inventoryReq) //<----From body will not carry data from call

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,612 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,507 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Konstantinos Passadis 19,246 Reputation points MVP
    2023-04-21T15:12:44.7233333+00:00

    Hello @Donald T Hess ! According to the HTTP/1.1 specification, GET requests should not have a message body. This is because GET is designed to retrieve information and should be idempotent (i.e., multiple identical requests should have the same effect as a single request). Including a body in a GET request can lead to unexpected behavior and is generally not recommended. However, if you must send sensitive data in the request without using query parameters, you should consider using a POST request instead. POST requests are designed to submit data and can have a request body. Here's an example of how you can modify your existing controller action to use POST:

    [HttpPost("api/inventory/search")] // Change this to POST
    [Produces("application/json")]
    public async Task<IActionResult> SearchInventory(
        [FromHeader] string tenant,
        [FromBody] GetInventoryRequest inventoryReq) // FromBody should work with POST
    {
        // Your implementation here
    }
    
    

    I hope i helped ! Kindly mark the answer as accepted in case it helped you ! BR


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.