首页 > 解决方案 > 从另一个类访问时,ModelState 引用不同

问题描述

我有一个名为ServiceController的 Controller 类,它的 ModelState 作为引用传递到另一个名为RequestValidator的验证类的实例中。当 ServiceController 收到请求时,它的 RequestValidator 类实例会检查 ModelState 是否有效。问题是,对于错误的输入,IsValidServiceController 自己的 ModelState 的值返回false(这是预期的),但IsValidValidator 的 ModelState 的值是true.

以下是有关如何设置这两个类的一些代码:

[Authorize]
[ApiController]
public class ServiceController : ControllerBase
{
    private readonly RequestValidator validator;

    //This is the ServiceController's contructor:
    public ServiceController(RequestValidator validator)
    {
        //A validator instance is passed in, which is used by this ServiceController instance
        this.validator = validator;
        
        //The validator's ModelState is set to point to the ModelState of the ServiceController
        this.validator.ModelState = this.ModelState; // This is the ONLY point in my ServiceController code where validator.ModelState is written to
    }

    [HttpPost]
    [Route("v0.1/users")]
    public async Task<ActionResult<User>> ProvisionUser(
        [FromBody] UserProvisioningRequest userRequest)
    {
        //But when an erroneous request comes, both ModelStates give different IsValid value:
        
        //The following two variables should have same value, but they don't at runtime.
        bool thisModelStateValidation = this.ModelState.IsValid;
        bool validatorModelStateValidation = this.validator.ModelState.IsValid;
        
        //The hashcodes of both ModelStates are also different
        int thisModelStateHashCode = this.ModelState.GetHashCode();
        int validatorModelStateHashCode = this.requestPayloadValidator.ModelState.GetHashCode();

        this.validator.ValidateRequest(userRequest);
    }
}


public class RequestValidator
{
    public ModelStateDictionary ModelState { get; set; }

    public void ValidateRequest(UserProvisioningRequest userRequest)
    {
        if (!this.ModelState.IsValid) // ---> At this point, IsValid is true, whereas it should be false
        {
            
        }
    }
}

正如上面代码注释中提到的,即使两个 ModelState 的哈希码也不同。但我不明白为什么会这样,因为值this.validator.ModelState总是写入 ONCE。可以解释的唯一方法是如果this.ModelState以某种方式重置,但我不明白为什么会发生这种情况。

标签: c#asp.net-mvcasp.net-coremodelstate

解决方案


推荐阅读