Add custom status code to all responses in mvc web api

Posted by Jpchoudhari under ASP.NET Web API on 3/3/2015 | Points: 10 | Views : 1315 | Status : [Member] | Replies : 1
I am using web api and I want to send proper status code along with the response. Currently it always returns 200 OK status.

I would like to send different response status like

on POST 201 Record Created
on PUT 205 Record Modified
on PUT 412 Validation Failed
on DELETE 204 Record Deleted etc.

These are quite standard status codes I found and all actions in web api accepts these request types.

I am currently struggling to find a clear example of how, in one place (most probably via action filter or http module) I can add that status code.

Kind Regards,


Posted by: Jitendrasoft09 on: 3/7/2015 [Member] [MVP] Starter | Points: 25


You can achieve with override OnActionExcecuted method to get the all action response and change to your status code as per convenience format, please refer code and link which are shared as below given-

 var response = new HttpResponseMessage

StatusCode = your code,
ReasonPhrase = your reason,
Content = new StringContent(reason)
throw new HttpResponseException(response);

Jitendra Kumar
If my post helps you, plz mark as an answer.

Jpchoudhari, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response