Search code examples
authenticationaccess-tokenasp.net-core-webapimodel-validation

Validate model after adding updating model


I am working on a web api on .net core. I am trying to validate/revalidate a model after adding additional data into the model (namely after adding the currently logged in user's username).

Let's say this is my controller's action

[Authorize]
[HttpPost]
public void Update([FromBody]UpdateUser User)

And here is the code I used for my authentication Scheme:

string token = Context.Request.Query["token"];
if (token == null) return AuthenticateResult.Fail("No JWT token provided");
try
{
    var principal = LoginControl.Validate(token);
    return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
}
catch (Exception)
{
    return AuthenticateResult.Fail("Failed to validate token");
}

Basically I am trying to achieve this flow: Post request -> Authorize-> add the user ID into the model -> validate the model.

So after authorized, I need to first add User.UserName = CurrentUserName and only the model needs to be validated, after which I can use the ModelState object on the newly updated model. As of now I am trying the following:

[HttpPost]
public async Task Update([FromBody]UpdateUser User)
{
    User.UserName = "hello";
    bool valid = await TryUpdateModelAsync(User);
    valid = TryValidateModel(User);
}

Right now at both instances valid is false and the ModelState shows that UserName is required. The only validation I had added in UpdateUser is adding [Required] in the model.


Solution

  • I got it working by clearing the model before calling TryValidateModel.

    [HttpPost]
    public async Task Update(UpdateUser User)
    {
        User.UserName = "hello";
        ModelState.Clear();
        TryValidateModel(User);
        // ModelState is now reset
    }