This is a job for the Dynamic Language Runtime and specifically ExpandoObject, whereby you return only the properties you need as determined at runtime:
public dynamic GetPerson()
{
bool firstNameRequired = true; // TODO: Parse querystring
bool lastNameRequired = false; // TODO: Parse querystring
dynamic rtn = new ExpandoObject();
if (firstNameRequired)
rtn.first_name = "Steve";
if (lastNameRequired)
rtn.last_name = "Jobs";
// ... and so on
return rtn;
}
void Main()
{
// Using the serializer of your choice:
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(GetPerson()));
}
Output:
{"first_name":"Steve"}
I don't have the means to test it right now [I have something similar in production on vanilla Web API, with a large number of optional fields], but going by the .NET Core docs the web method would look something like this albeit without the hard coded values!:
[HttpGet()]
public IActionResult Get([FromQuery(Name = "fields")] string fields)
{
var fieldsOptions = fields.Split(',');
dynamic rtn = new ExpandoObject();
if (fieldsOptions.Contains("FirstName"))
rtn.first_name = "Steve";
if (fieldsOptions.Contains("LastName"))
rtn.last_name = "Jobs";
if (fieldsOptions.Contains("Email"))
rtn.email = "[email protected]";
return new ObjectResult(rtn);
}
You would need to reference the System.Dynamic.Runtime package.
$selectproperty however Core support is spotty at best.