Say I have these 2 classes
class Car {
public string CarName {get;set;}
}
class EmployeeCar:Car {
public string EmployeeName {get;set;}
}
When I call this API
[HttpGet]
public Car GetCar(Employee employee) {
return GetEmployeeCar(employee);
}
assuming
private EmployeeCar GetEmpoyeeCar(Employee employee) {
return new EmployeeCar { CarName: "Car 1", EmployeeName: "Employee 1" };
}
I am getting this
{ CarName: "Car 1", EmployeeName: "Employee 1" }
Note that EmployeeName
does not belong to Car
.
How can I get the API to return only the properties of Car
? (which is the return type of the API) ie.
{ CarName: 'Car 1' }
SOLUTION
This is much longer than I hoped (not sure if there is a shorter version) but I hope this can help someone
public Car GetCar(Employee employee) {
Car carDirty = GetEmployeeCar(employee); // { CarName: "Car 1", EmployeeName: "Employee 1" }
Car carClean = SweepForeignProperties(carDirty); // Only keep properties of Car
return carClean; // { CarName: "Car 1" }
}
/// <summary>Only keep T's own properties, getting rid of unknown/foreign properties that may have come from a child class</summary>
public static T SweepForeignProperties<T>(T dirty) where T: new()
{
T clean = new T();
foreach (var prop in clean.GetType().GetProperties())
{
if (prop.CanWrite)
prop.SetValue(clean, dirty.GetType().GetProperty(prop.Name).GetValue(dirty), null);
}
return clean;
}