1

I have the following Api Controller:

[HttpPost]
public User Create(User user)
{
    User user = _domain.CreateUser(user);
    //set location header to /api/users/{id}
    //set status code to 201
    //return the created user
}

It seems like we have to depend on Request.CreateResponse(..) and change the signature of the controller so as to return IHttpActionResult.

I do not want to change the method signature as it is very useful for the documentation purpose. I am able to add the Location header using HttpContext.Current.Response... but not able to set the status code.

Anybody has any better idea on this?

1 Answer 1

2

Because you are using a custom (other) return type outside of void, HttpResponseMessage, and IHttpActionResult - it's harder to specify the status code. See Action Results in Web API 2.

From Exception Handling in Web API. If you want to stick with not modifying the return type then this might be something you can do to set the status code:

[HttpPost]
public User Create(User user)
{
    User user = _domain.CreateUser(user);
    //set location header to /api/users/{id}

    //set status code to 201
    if (user != null)
    {
        //return the created user
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Created, user);
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError));        
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

this is not a good answer. it doesn't deserve a downvote because it does exactly what it says, but throwing exceptions to get the desired behavior here is WAY hacky.
Use an exception to indicate a normal result is not a reasonable answer.
From the two articles, it is the recommended way by www.asp.net to set a specific status code and return a custom object.

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.