Returning a 403 from a custom model binder

Viewed 623

We are using some custom model binders for our .Net Core api and have some logic in the model binder which should sometimes result in a 403 being returned by our api.

I am aware that you can use Mvc.ModelBinding.ModelBindingResult.Failed() to return a 400 when model binding fails, however if it is due to fail as ar result of an attempt at Unauthorized access then we need to return a 403, ideally with a custom message.

3 Answers

It is possible to call bindingContext.ModelState.AddModelError("Unauthorized", "Reason") within your ModelBinder implementation.

Then inside the controller you can use if(ModelState.IsValid) to assert if the ModelBinder worked correctly and if you had any validation errors in the process.

In your case you can then check if is is not valid and handle an unauthorised response in the controller as you normally would.

I would reserve ModelBindingResult.Failed() for catastrophic errors in model binding that are not intended (e.g. caused by malformed requests), as opposed to an intended behaviour that is desired by the developer.

Related