10

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;
}
3
  • the error is right, you should consider to return Task<IHttpActionResult> and change the return to return Ok(myObject); Commented Feb 3, 2016 at 2:24
  • In WebAPI, you throw an exception with a specific response code (represented by an Enum). It doesn't let the exception bubble up the stack, but simply returns the status code you specify. throw new HttpResponseException(HttpStatusCode.NotFound); Commented Feb 3, 2016 at 9:48
  • @James Thank you for your response but I'm having a hard time finding the HttpResponseException. Looks like it's in the System.Web.Http namesapce but my ASP.NET Core 1.0 doesn't even let me reference it. It's suggesting I install this NuGet package nuget.org/packages/Microsoft.AspNet.Mvc.WebApiCompatShim Is this still the right way to handle it in ASP.NET Core 1.0? Commented Feb 3, 2016 at 21:41

1 Answer 1

12

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your suggestion but I shouldn't have to do any of that. I shouldn't have to install a compatibility package to make ASP.NET Core 1.0 API behave more like the old version either. What I really want to learn is the right way of returning HttpStatus codes in ASP.NET Core 1.0 APIs.
Thanks again for your help. This is where I get the error "Cannot implicitly convert type 'HttpStatusCodeResult' to 'SomeObject'. This is exactly what I've been struggling with.
Sorry! I take it back! Just noticed you're returning IActionResult and sending the object along with the StatusCode. This does work fine. Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.