I have the following endpoint implemented in .Net Core 3.1 WebApi. The TestFilter object has a list parameter TestTypes. TestTypes gets a default TestType value once it is constructed. When the endpoint gets called with the TestFilter parameter I would expect that the default value would be replaced with the incoming value. Instead it's added to the list so the default value is still part of it.
This worked when using .Net472 but after migrating to .Net Core 3.1 the default value is always part of the array.
Is there a way to specify to overwrite the default parameter value if it's supplied by the client?
[HttpPost]
[Route("test")]
public async Task<IHttpActionResult> GetTests([FromBody] TestFilter filter)
{
// Call repo
}
public class TestFilter
{
public IReadOnlyCollection<TestType> TestTypes { get; set; }
public string Description;
TestFilter() {
TestTypes = new List
{
new TestType("AdvancedTest", 10)
};
}
}
CodePudding user response:
Try to change your TestFilter
like this:
public class TestFilter
{
public IReadOnlyCollection<TestType> TestTypes { get; set; } = new List<TestType>{new TestType("AdvancedTest", 10)};
public string Description;
}
TestType:
public class TestType
{
public string v1 { get; set; }
public int v2 { get; set; }
public TestType() { }
public TestType(string v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
}
Update:
I use the following classes and it can work.
public class TestFilter: TestBaseFilter
{
public string Description;
}
public class TestBaseFilter
{
public IReadOnlyCollection<TestType> TestTypes { get; set; } = new List<TestType> { new TestType("AdvancedTest", 10) };
}