【问题标题】:valid model c# properties有效的模型 C# 属性
【发布时间】:2017-10-07 10:00:00
【问题描述】:

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

例如,我有一个模型

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

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

然后在请求中我发送这个正文:

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

问题是验证通过了,例如我需要发送类似“属性不允许”之类的响应

【问题讨论】:

  • 为什么传递其他属性是否重要?为什么你希望它验证失败?
  • 我需要向用户表明此属性或其他属性在控制器中不起作用或不允许,在这种情况下是因为 api 是公共的,我需要表明它可以和不能执行api

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


【解决方案1】:

您可以使用 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 的使用情况,当然可能有更好的方法来做到这一点。当然,应该检查上面的代码是否存在一些明显的可能错误情况,但这可能是第一次尝试。

【讨论】:

  • 这个解决方案很酷,但是deep json有问题,并且和注解存在冲突,因为例如一些属性是可选的,这个解决方案非常强大的属性,但是很好开始,非常感谢!
【解决方案2】:

非常好的验证库是FluentValidation

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多