【问题标题】:FromBody value not overwriting default parameter value after migrating to .net core迁移到 .net 核心后,FromBody 值不会覆盖默认参数值
【发布时间】:2021-10-07 12:57:50
【问题描述】:

我在 .Net Core 3.1 WebApi 中实现了以下端点。 TestFilter 对象有一个列表参数TestTypes。 TestTypes 在构造后会获得一个默认的 TestType 值。当使用 TestFilter 参数调用端点时,我希望默认值将替换为传入值。相反,它被添加到列表中,因此默认值仍然是其中的一部分。

这在使用 .Net472 时有效,但在迁移到 .Net Core 3.1 后,默认值始终是数组的一部分。

如果默认参数值是由客户端提供的,有没有办法指定覆盖默认参数值?

    [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)
                      };
    }
}

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    尝试像这样更改您的TestFilter

    public class TestFilter
            {
                public IReadOnlyCollection<TestType> TestTypes { get; set; } = new List<TestType>{new TestType("AdvancedTest", 10)};
                public string Description;
    
            }
    

    测试类型:

    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;
                }
            }
    

    结果:

    更新:

    我使用以下类,它可以工作。

    public class TestFilter: TestBaseFilter
            {
                
                public string Description;
    
            }
            public class TestBaseFilter
            {
                public IReadOnlyCollection<TestType> TestTypes { get; set; } = new List<TestType> { new TestType("AdvancedTest", 10) };
            }
    

    【讨论】:

    • 感谢您的建议,但不幸的是它也不起作用
    • 我在.net core 3.1中测试过,可以用,你可以看看更新后的答案。
    • 很好,如果你把初始化放到构造函数中也可以吗?
    • 不,我删除了我的回答中的构造函数。
    • 是的,它可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    相关资源
    最近更新 更多