jsonasp.net-coreentity-framework-coregetpostman

The x field is required error in EF Core requests


If got a controller endpoint expecting a DTO with just a list of Ids to fetch this specific list of IDs. When sending the following request to the endpoint, it returns an error

the idList field is required

I tried sending it multiple ways.

This is the controller method in question:

[HttpGet("listById")]
public async Task<IActionResult> ListById([FromBody] IdListDto idList) =>
       await Handle(Service.FindByList(idList));

The DTO:

public record IdListDto : IIdListDto
{
    public ulong[]? Ids { get; set; }
}

Postman request and result:

Postman-Request and Result

I tried changing the request in different ways, like wrapping the "Ids" parameter in an idList JSON object, but the result is the same. I don't actually need the DTO and tried using just a simple array, but it didn't recognize that either.

Any ideas on how to solve this?


Solution

  • The reason of the issue is using [FromBody] in a GET request. You cannot use [FromBody] in a "GET" request. Simply because GET requests have no body.

    What you can do is to use [FromQuery] instead. Your code should look like the one below

    [HttpGet(Name = "listById")]
    public async Task<IActionResult> ListById([FromQuery] ulong[]? idList) =>
        await Handle(Service.FindByList(idList));
    

    Moreover, you must call the GET action above like the following URL with query parameters

    yourdomain.com/..../listById?idList=1&idList=2&idList=3

    Update: If you are worried about the limit of the query parameter length on that your webserver can accept, you can change this limit like this for IIS:

    <system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxQueryString="1024" maxUrl="2048">
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
    </security>
    </system.webServer>