Babu James
Babu James

Reputation: 2843

ASP.NET Web API set custom status code

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?

Upvotes: 1

Views: 2547

Answers (1)

Nhan
Nhan

Reputation: 1474

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));        
    }
}

Upvotes: 2

Related Questions