Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object to Web API as Parameter with HttpGet

I am working on .NET 6.0 Web API application. I need to pass object which is collection of string list to API with the purpose it will return data. I can do with HttpPost but since I am designing this API for the purpose of Get Record, what will be the right approach?

public class JobRoleDataView
{
    public JobRoleDataView() { }

    public List<string> Roles { get; set; }
}

this object will get more properties soon so it is not just List...

[HttpGet("SearchRecord")]
public async Task<IActionResult> SearchRecord(JobRoleDataView JobRoles)
{
  //remaining code

  return Ok(returnResponse);
}

error

   TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
like image 431
K.Z Avatar asked Sep 04 '25 01:09

K.Z


1 Answers

You can use [FromQuery] attribute and pass roles as querystring.

 [HttpGet("SearchRecord")]
public async Task<IActionResult> SearchRecord([FromQuery]JobRoleDataView JobRoles)
{
  //remaining code

  return Ok(returnResponse);
}
}

The request url will be seen as below. https://localhost:7009/WeatherForecast/SearchRecord?Roles=vishal&Roles=michel

like image 167
Vishal Pawar Avatar answered Sep 07 '25 19:09

Vishal Pawar