有效的模型c#属性

时间:2017-10-07 10:00:01

标签: c# asp.net-web-api annotations asp.net-web-api2

有人知道,如何不允许控制器中的其他属性使用注释或其他方法?

例如,我有一个模型

[required]
public string user_name {get;set;}

[required]
public string password {get;set;}

然后在请求中我发送了这个身体:

{
"user_name" : "user",
"password" : "12345",
"other_property" : "here is the problem"
}

问题是验证通过了,我需要例如发送响应,例如"属性不允许"

2 个答案:

答案 0 :(得分:0)

您可以编写一个使用JSON.NET验证泛型类型的简单扩展方法:

static class ValidationExtensions
{
    public static void ValidateNoUnknownProperties<TValid>(this string json)
    {
        var validPropertyNames = typeof(TValid).GetProperties().Select(p => p.Name).ToList();
        var deserializedJson = JObject.Parse(json);
        var invalidPropertyNames = deserializedJson.Properties()
                                       .Where(p => !validPropertyNames.Contains(p.Name))
                                       .Select(p => p.Name)
                                       .ToList();

        if (invalidPropertyNames.Count() > 0)
        {
            throw new Exception($"Invalid Properties: {string.Join(",", invalidPropertyNames)}");
        }
    }
}

用法:

class Dto
{
    public string user_name { get; set; }

    public string password { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var json = @"
        {
            ""user_name"" : ""user"",
            ""password"" : ""12345"",
            ""other_property"" : ""here is the problem"",
            ""something_else"" : ""yeah...""
        }";

        json.ValidateNoUnknownProperties<Dto>();
    }
}

输出:

Invalid Properties: other_property,something_else"

编辑:根据您对JSON的使用情况,当然可能有更好的方法来执行此操作。当然,上面的代码应该检查一些明显可能的错误情况,但它可能是第一次拍摄。

答案 1 :(得分:0)

非常好的库使验证成为FluentValidation