0

我无法进入我的自定义RequiredAttribute。

我已经按照这篇文章如何:调试 .NET Framework 源代码

在工具 > 选项 > 调试 > 常规中:

我已经Enable .NET Framework source stepping打勾

我已Enable Just My Code取消勾选

我创建了一个带有单元测试的自定义RequiredAttribute 的基本示例:

using System.ComponentModel.DataAnnotations;

public class CustomRequiredAttribute : RequiredAttribute
{
    public bool IsValid(object value, object container)
    {
        if (value == null)
        {
            return false;
        }

        string str = value as string;

        if (!string.IsNullOrWhiteSpace(str))
        {
            return true;
        }

        return false;
    }
}

此测试模型使用:

public class CustomRequiredAttributeModel
{
    [CustomRequired]
    public string Name { get; set; }
}

这是单元测试(正确通过了断言):

    [Fact]
    public void custom_required_attribute_test()
    {
        // arrange
        var model = new CustomRequiredAttributeModel();
        var controller = AccountController();

        // act
        controller.ValidateModel(model);

        // assert
        Assert.False(controller.ModelState.IsValid);
    }

单元测试使用这个辅助方法:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;

public static class ModelHelper
{
    public static void ValidateModel(this Controller controller, object viewModel)
    {
        controller.ModelState.Clear();

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

        Validator.TryValidateObject(viewModel, validationContext, validationResults, true);

        foreach (var result in validationResults)
        {
            if (result.MemberNames.Any())
            {
                foreach (var name in result.MemberNames)
                {
                    controller.ModelState.AddModelError(name, result.ErrorMessage);
                }
            }
            else
            {
                controller.ModelState.AddModelError("", result.ErrorMessage);
            }
        }
    }
}
4

1 回答 1

1

在您的 CustomRequiredAttribute 中更改您的方法以使用覆盖,

public class CustomRequiredAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        string str = value as string;

        if (!string.IsNullOrWhiteSpace(str))
        {
            return true;
        }

        return false;
    }
}
于 2013-10-07T01:58:57.703 回答