c# - 从另一个类访问时,ModelState 引用不同
问题描述
我有一个名为ServiceController的 Controller 类,它的 ModelState 作为引用传递到另一个名为RequestValidator的验证类的实例中。当 ServiceController 收到请求时,它的 RequestValidator 类实例会检查 ModelState 是否有效。问题是,对于错误的输入,IsValid
ServiceController 自己的 ModelState 的值返回false
(这是预期的),但IsValid
Validator 的 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
以某种方式重置,但我不明白为什么会发生这种情况。
解决方案
推荐阅读
- google-cloud-platform - GCP - 在我的应用中使用 google plus 登录是否需要付费?
- spring - 2天后如何在java中调用rest API
- php - 如何使用集合 laravel 更改数组
- django - 如何将多个 ManytoMany 实例保存到 Django 对象?
- python - 如何将剪影分数附加到列表中
- python - 如何从没有重复元素的列表中创建字典
- python-3.x - 为什么我的 python 无法读取桌面上的文件?
- python - 如何在频谱图中标准化
- python - 如果 3rd 方 api 服务正在使用上传文件,则通过 selenium 上传文件
- python - 如何测量numpy数组区域的平均值