Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return HttpStatusCode in API method

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;
}
like image 730
Sam Avatar asked Feb 03 '16 02:02

Sam


1 Answers

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;
}
like image 83
peco Avatar answered Oct 12 '22 09:10

peco