How do I return an HttpStatus code from API methods in my ASP.NET Core 1.0 if there's a problem?
If the method is supposed to return a particular object type, when I try return an Http status code, I get an error saying I can't convert my object to status code.
[HttpPost]
public async Task<SomeObject> Post([FromBody] inputData)
{
// I detect an error and want to return BadRequest HttpStatus
if(inputData == null)
return new HttpStatusCode(400);
// All is well, so return the object
return myObject;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With