为 Custom Model Binder 赋值时出现问题

Issue when assigning values to Custom Model Binder

我得到

An exception of type 'System.NullReferenceException' occurred in *****Tests.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

如何正确给绑定模型赋值?

public class PersonRegistration
{
    RegisterBindingModel model;
    [TestMethod]
   
    public void TestMethod1()
    {
        AccountController ac = new AccountController(userManager, loggingService);
        model.UserName = "test123@gmail.com";
        var result = ac.Register(model);
        Assert.AreEqual("User Registered Successfully", result);
    }

我在执行时遇到异常 model.UserName = "test123@gmail.com";

public class RegisterBindingModel
{
    public RegisterBindingModel();
    [Display(Name = "User name")]
    [Required]
    public string UserName { get; set; }
}

您的 RegisterBindingModel model 未初始化。

For this reason unhandled null exception (Object reference not set to an instance of an object).occurred.

所以尝试这样的事情:

public class RegisterBindingModel
{   
    [Display(Name = "User name")]
    [Required]
    public string UserName { get; set; }
}

public class PersonRegistration
{
    RegisterBindingModel model= new RegisterBindingModel ();//initialized
    [TestMethod]

    public void TestMethod1()
    {
        AccountController ac = new AccountController(userManager, loggingService);
        model.UserName = "test123@gmail.com";
        var result = ac.Register(model);
        Assert.AreEqual("User Registered Successfully", result);
    }

此错误消息有点神秘,但它表示您认为不是的某些内容为空。

RegisterBindingModel model; 没有实例。给它一个,它应该可以工作。如果仍然出错,请将所有内容包装在 try catch 中并进行调试。

RegisterBindingModel model = new RegisterBindingModel();

您声明了一个模型,但没有初始化它以使其指向内存中的某个位置。尝试写作 RegisterBindingModel 模型 = new RegisterBindingModel();