Search code examples
c#entity-framework-coreasp.net-core-mvcmodel-validation

ASP.NET Core : TryValidateModel throws NullReferenceException when Controller calls another Controller


I have an ASP.NET Core MVC view that contains different types of entities. The view is handled by a MainController that calls the individual entities' controller based on a discriminator. This has been working fine until I started using custom validation attributes that require my dbContext to lookup data from the database.

An example of the MainController calling an EntityController looks like this. I tried both creating a new controller instance (commented out) and direct dependency injection of the controller:

else if (strEntityIdentifier == "VGBKKA2")
{
    // var controller = new ValveControlsController(_context);
    // var JSONresult = await controller.Put(key, values);
    // controller.Dispose();

    var JSONresult = await _valveControlsController.Put(key, values);
}

In the individual entities' controllers I call the model validation like this:

var bValidate = TryValidateModel(model);

This throws a NullReferenceException when the controller method is called by the MainController. However if I call the individual controller directly it works fine.

I also tried the validation via Objectvalidation:

var validationResultList = new List<ValidationResult>();
bool bValidate = Validator.TryValidateObject(model, new ValidationContext(model) , validationResultList, true);

This doesn't throw a NullReferenceException but instead I cannot get my dbContext in the custom ValidationAttribute via

var _context = (SvrContext)validationContext.GetService(typeof(SvrContext));

which is working fine with the TryValidateModel approach.

Any help is appreciated!


Solution

  • I solved this by redirecting the request via RedirectToAction from the MainController to the corresponding EntityController. Thanks to @Alexander for the hint!