首页 > 解决方案 > DotNet CORE API - 如何防止正文中的附加属性

问题描述

我想防止用户在我的 API 中发布/修补时将附加属性放在正文中。

假设我们有以下模型:

{ "test": "value"}

如果用户发布以下内容:

{ "test": "value", "anotherProp":"value"}

我想返回一个 BadRequestResult (400),因为不需要“anotherProp”。我想要的只是一个具有“测试”属性的主体。

标签: c#asp.net-core

解决方案


给你。按照下面代码中的注释进行操作...

    public class MyObject
    {
        public string MyProperty { get; set; }
    }

    class Program
    {
        static void Main()
        {
            // This is a valid json instance of MyProperty
            string json1 = "{\"MyProperty\" : \"foobar\"}";

            // This is NOT a valid json instance of MyProperty, as it has an unwanted property.
            string json2 = "{\"MyProperty\" : \"foobar\", \"MyProperty2\" : \"foobar2\"}";

            // This will deserialize 'json1' into MyProperty
            MyObject myObject1 = JsonConvert.DeserializeObject<MyObject>(json1);

            // This will deserialize 'json2' into MyProperty, ignoring the unwanted property.
            MyObject myObject2 = JsonConvert.DeserializeObject<MyObject>(json2);

            try
            {
                // This will throw an error: Could not find member 'MyProperty2' on object of type 'MyObject'.
                JsonConvert.DeserializeObject<MyObject>(json2, new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Error
                });
            }
            catch (JsonSerializationException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

这是关于此的文档: https ://www.newtonsoft.com/json/help/html/DeserializeMissingMemberHandling.htm


推荐阅读