无法单步执行 MVC 自定义必需属性

本文关键字:属性 自定义 MVC 单步 执行 | 更新日期: 2023-09-27 18:34:06

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

我已关注本文如何:调试 .NET 框架源代码

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

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);
            }
        }
    }
}

无法单步执行 MVC 自定义必需属性

在自定义属性中,将方法更改为使用覆盖,

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;
    }
}