Return HttpStatusCode in API method
Return an IActionResult
from your controller action instead:
public async Task<IActionResult> Post([FromBody] InputData inputData){ if(inputData == null) { return new HttpStatusCodeResult((int) HttpStatusCode.BadRequest); } //... return Ok(myObject);}
If you instead want to remove such null checks from the controller you could define a custom attribute:
public class CheckModelForNullAttribute : ActionFilterAttribute{ public override void OnActionExecuting(ActionExecutingContext context) { if (context.ActionArguments.Any(k => k.Value == null)) { context.Result = new BadRequestObjectResult("The model cannot be null"); } }}
This way we dont have to bother with the model being null in the action.
[HttpPost][CheckModelForNull]public async Task<SomeObject> Post([FromBody]InputData inputData){ // My attribute protects me from null // ... return myObject;}