如何返回验证结果?

发布于 2024-12-12 08:05:47 字数 895 浏览 0 评论 0原文

我有一个 ASP.NET MVC 站点,它使用 CommandService。该命令服务负责执行命令,但在执行每个命令之前需要验证每个命令,因此有一个返回 ValidationResult 的 Validate 操作,看起来像(简化的):

public class ValidationResult
{
  public List<string> ErrorCodes { get; set; }
}

我想改进这一点,因为当前有一个列表返回字符串,例如“UserDoesNotExist”或“TitleIsMandatory”,当然这不是最好的方法。

最好返回强类型的东西。但我怎样才能做到这一点呢?

选项 1:使用一个大枚举,例如:

public enum ErrorCode { UserDoesNotExist, TitleIsMandatory}

public class ValidationResult
{
  public List<ErrorCode> ErrorCodes { get; set; }
}

我不知道创建这么大的枚举并将所有域错误代码放入其中是否是一个好主意?

选项 2:使用类

public class ErrorCode {}
public class UserDoesNotExist : ErrorCode {}
public class TitleIsMandatory : ErrorCode {}

public class ValidationResult
{
  public List<ErrorCode> ErrorCodes { get; set; }
}

更干净,但更难使用?

你会怎么做,或者我错过了其他选择?

I have an ASP.NET MVC site, that uses a CommandService. This command service is responsible for executing the commands, but before they are executed each command needs to be validated, so there's a Validate operation that returns a ValidationResult, that looks like (simplified):

public class ValidationResult
{
  public List<string> ErrorCodes { get; set; }
}

I would like to improve this, because currently a list of strings is returned, like 'UserDoesNotExist' or 'TitleIsMandatory', and this is not the best approach of course.

It would be better to return something strongly typed. But how can I do that?

Option 1: use one big enum like:

public enum ErrorCode { UserDoesNotExist, TitleIsMandatory}

public class ValidationResult
{
  public List<ErrorCode> ErrorCodes { get; set; }
}

I don't know if it's a good idea to create such a big enum and put all domain error codes in it?

Option 2: use classes

public class ErrorCode {}
public class UserDoesNotExist : ErrorCode {}
public class TitleIsMandatory : ErrorCode {}

public class ValidationResult
{
  public List<ErrorCode> ErrorCodes { get; set; }
}

Is cleaner, but harder to use?

What would you do, or did I miss other options?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

所以这就是我解决它的方法。首先,主 ValidationResult 类如下所示:

 public class ValidationResult
{        
    public List<ValidationResultItem> ValidationResultItems { get; set; }

    public bool IsAcceptable
    {
        get { return (ValidationResultItems == null || !ValidationResultItems.Any(vri => !vri.IsAcceptable)); }
    }       

    public void Add(ValidationResultItem propertyValidationResultItem)
    {
        ValidationResultItems.Add(propertyValidationResultItem);
    }

    public void Add(IEnumerable<ValidationResultItem> validationResultItems)
    {
        ValidationResultItems.AddRange(validationResultItems);
    }       
}

ValidationResultItem 是一个抽象类:

public abstract class ValidationResultItem
{
    private ResultType _resultType;

    protected ValidationResultItem(ResultType resultType, string message)
    {
        ResultType = resultType;
        Message = message;
    }

    public bool IsAcceptable { get; private set; }
    public string Message { get; private set; }
    public ResultType ResultType
    {
        get { return _resultType; }
        set { _resultType = value; IsAcceptable = (_resultType != ResultType.Error); }
    } 
}

它有两种实现:

public class PropertyValidationResultItem : ValidationResultItem
{        
    public PropertyValidationResultItem(ResultType resultType, string message, string propertyName, object attemptedValue) : base(resultType, message)
    {            
        PropertyName = propertyName;           
        AttemptedValue = attemptedValue;
    }

    public string PropertyName { get; private set; }        
    public object AttemptedValue { get; private set; }             
}

每个

public abstract class BusinessValidationResultItem : ValidationResultItem
{
    protected BusinessValidationResultItem(ResultType resultType, string message) : base(resultType, message)
    {
    }
}

命令处理程序都有自己的 BusinessValidationResultItem 实现,例如:

public class AddArticleBusinessValidationResultItem : BusinessValidationResultItem
{
    public enum AddArticleValidationResultCode { UserDoesNotExist, UrlTitleAlreadyExists, LanguageDoesNotExist }

    public AddArticleBusinessValidationResultItem(ResultType resultType, string message, AddArticleValidationResultCode code)
        : base(resultType, message)
    {
        Code = code;
    }

    public AddArticleValidationResultCode Code { get; set; }
}

这意味着如果客户端获取 ValidationResult,他可以强制转换BusinessValidationResultItem 到具体的 AddArticleBusinessValidationResultItem ,因此在 switch 语句中使用特定枚举 - 避免魔术字符串。

So this is the way I solved it. First, the main ValidationResult class looks like:

 public class ValidationResult
{        
    public List<ValidationResultItem> ValidationResultItems { get; set; }

    public bool IsAcceptable
    {
        get { return (ValidationResultItems == null || !ValidationResultItems.Any(vri => !vri.IsAcceptable)); }
    }       

    public void Add(ValidationResultItem propertyValidationResultItem)
    {
        ValidationResultItems.Add(propertyValidationResultItem);
    }

    public void Add(IEnumerable<ValidationResultItem> validationResultItems)
    {
        ValidationResultItems.AddRange(validationResultItems);
    }       
}

ValidationResultItem is an abstract class:

public abstract class ValidationResultItem
{
    private ResultType _resultType;

    protected ValidationResultItem(ResultType resultType, string message)
    {
        ResultType = resultType;
        Message = message;
    }

    public bool IsAcceptable { get; private set; }
    public string Message { get; private set; }
    public ResultType ResultType
    {
        get { return _resultType; }
        set { _resultType = value; IsAcceptable = (_resultType != ResultType.Error); }
    } 
}

and there are two implementations of it:

public class PropertyValidationResultItem : ValidationResultItem
{        
    public PropertyValidationResultItem(ResultType resultType, string message, string propertyName, object attemptedValue) : base(resultType, message)
    {            
        PropertyName = propertyName;           
        AttemptedValue = attemptedValue;
    }

    public string PropertyName { get; private set; }        
    public object AttemptedValue { get; private set; }             
}

and

public abstract class BusinessValidationResultItem : ValidationResultItem
{
    protected BusinessValidationResultItem(ResultType resultType, string message) : base(resultType, message)
    {
    }
}

Each command handler has its own implementation of BusinessValidationResultItem, for example:

public class AddArticleBusinessValidationResultItem : BusinessValidationResultItem
{
    public enum AddArticleValidationResultCode { UserDoesNotExist, UrlTitleAlreadyExists, LanguageDoesNotExist }

    public AddArticleBusinessValidationResultItem(ResultType resultType, string message, AddArticleValidationResultCode code)
        : base(resultType, message)
    {
        Code = code;
    }

    public AddArticleValidationResultCode Code { get; set; }
}

This means that if the client gets a ValidationResult, he can cast the BusinessValidationResultItem to the concrete AddArticleBusinessValidationResultItem and so use the specific enumeration in a switch statement - avoiding magic strings.

全部不再 2024-12-19 08:05:47

我的 REST api 非常相似,如果存在验证错误,则会将字符串消息与对象一起返回给用户。

例如:

[DataContract]
public class ApiErrorResult : ApiResult<IList<ErrorCodes>>
{
    public ApiErrorResult(String message)
    {
        Code = ApiCode.ValidationError;
        Error = message;
    }
}

那么 ApiResult 是:

public class ApiResult<T>
{

    [DataMember]
    public ApiCode Code
    {
        get;
        set;
    }

    [DataMember]
    public String Error
    {
        get;
        set;
    }

    [DataMember]
    public T Context
    {
        get;
        set;
    }
}

因此,如果它是验证错误,则上下文将包含等效的验证错误代码。如果不是,我将实际结果存储在上下文中并返回 ApiResult 而不是 ApiErrorResult

希望这会有所帮助。

My REST api is quite similar in the sense that if there is a validation error then a string message is returned to the user together with an object.

For example:

[DataContract]
public class ApiErrorResult : ApiResult<IList<ErrorCodes>>
{
    public ApiErrorResult(String message)
    {
        Code = ApiCode.ValidationError;
        Error = message;
    }
}

then ApiResult is :

public class ApiResult<T>
{

    [DataMember]
    public ApiCode Code
    {
        get;
        set;
    }

    [DataMember]
    public String Error
    {
        get;
        set;
    }

    [DataMember]
    public T Context
    {
        get;
        set;
    }
}

So if it is a validation error then the context will contain the equivalent validation error codes. If it isnt i store the actual result in the context and return an ApiResult instead of an ApiErrorResult

hope this helps somehow.

魄砕の薆 2024-12-19 08:05:47

当然这不是最好的方法。

为什么不呢?字符串有什么问题吗?如果您担心一致性,可以使用资源文件或常量。字符串在层之间会更便携,但这取决于您的设计。无论如何,您可能需要一个 ErrorCode(字符串或枚举)和一个 ErrorMessage(字符串)。我假设您需要将此错误转换为用户更可读的内容?

您应该研究评论之一中提到的内置验证。验证来自System.ComponentModel.DataAnnotations,与MVC无关。您可以在 MVC 范围之外进行验证,这是一个示例:

var validationContext = new ValidationContext(yourObject, null, null);
var validationResults = new List<ValidationResult>();

Validator.TryValidateObject(yourObject, validationContext, validationResults);

HTH...

and this is not the best approach of course.

Why not? Whats wrong with strings? If you are worried about consistency maybe use resource files or constants. Strings will be more portable in between layers but that depends on your design. Regardless, you will probably want an ErrorCode (string or enum) and an ErrorMessage (string). I am assuming you need to convert this error into something more readable to the user?

You should look into the built in validation as mentioned in one of the comments. The validation comes from System.ComponentModel.DataAnnotations, nothing to do with MVC. You can validate outside the scope of MVC, here is an example:

var validationContext = new ValidationContext(yourObject, null, null);
var validationResults = new List<ValidationResult>();

Validator.TryValidateObject(yourObject, validationContext, validationResults);

HTH...

南城追梦 2024-12-19 08:05:47

也许是一个愚蠢的观察,但为什么不在客户端进行验证呢?行为良好的客户端应该在提交命令之前验证命令。行为不当的客户端不会验证和提交,但也不会找回失败的原因(这有什么意义 - 即使从安全角度来看也是不可取的)。当然,在服务器端,您应该重新验证并以某种方式记录无效命令,以便运维人员知道他们需要解决/调查某些故障。如果您的客户采用不同的技术,那么在语言中立的 DSL 中定义验证并从该 DSL 中以您喜欢的任何技术/语言生成代码可能会很有用(不过这里还有其他选项)。

Maybe a stupid observation, but why not do the validation client-side? Well-behaved clients should validate commands before submitting them. Ill-behaved clients will not validate and submit, but also not get back the reason why it failed (what would be the point - even not advisable from a security POV). Of course, server-side you should re-validate and somehow log invalid commands so Ops knows there are failures they need to resolve/look into. If you have clients in different technology, it might be useful to define the validation in a language neutral DSL and generate code in any tech/lang you like from that DSL (there other options here, though).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文