-1

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!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ManCon25
  • 1
  • 2
  • 1
    You could redirect request to another controller or move logic to another component shared between the 2 controllers. – Alexander Mar 22 '23 at 16:02
  • If you added [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), it would be easier to tell. I'm not sure, at this stage. – Qing Guo Mar 23 '23 at 06:48
  • Thank you @Alexander the redirect was the way to go. I still don't understand why the original approach didn't work though. – ManCon25 Mar 23 '23 at 13:32

1 Answers1

0

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

ManCon25
  • 1
  • 2