c# - DotNet CORE API - 如何防止正文中的附加属性
问题描述
我想防止用户在我的 API 中发布/修补时将附加属性放在正文中。
假设我们有以下模型:
{ "test": "value"}
如果用户发布以下内容:
{ "test": "value", "anotherProp":"value"}
我想返回一个 BadRequestResult (400),因为不需要“anotherProp”。我想要的只是一个具有“测试”属性的主体。
解决方案
给你。按照下面代码中的注释进行操作...
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
推荐阅读
- interpolation - 如何在 R 中应用双线性插值
- javascript - 如何在多个文本文件中自动用生成的数字替换字符串并将它们命名为值?
- postgresql - 创建新服务器时出现 pgAdmin 4 错误。(无法连接到服务器:连接被拒绝)
- php - PHP减去两个数字给出错误的值
- python - Python - 在 Sentry 日志记录处理程序(django)中清理键
- hibernate - java - 如何在Java-EE中使用hibernate建立ManyToMany关系?
- java - 没有“springfox.documentation.schema.TypeNameExtractor”类型的合格bean
- asp.net-core - Ionic V3 请求在 Chrome 浏览器和模拟器中随机失败
- c - “)期望在第 7 行”传递结构数据时 c 程序中的错误
- intellij-idea - 让idevimrc快捷方式在选择多行的可视模式下工作