Reputation: 6590
I am developing webapi in mvc4. I want to create a class which contains Custom HttpStatusCode
which inherits HttpStatusCode
class. Let's suppose I have one signup
api which require user details like Firstname, Lastname, email, password etc. Suppose user enter email [email protected]
and I check if user already exists. If this email is already exists I want to return Custom HttpStatusCode. Suppose I have created 1001 HttpStatusCode
for email already exists.
I tried some thing like this
return new System.Web.Http.Results.ResponseMessageResult(
Request.CreateErrorResponse(
(HttpStatusCode)1001,
new HttpError("Email is already exists.")
)
);
But I don't know is it a correct way or not. When we use return Unauthorized();
it means it's an unauthorized access which returns 401 error code. In same way I want to create a custom response and status code. In my case suppose email id already exists then I should return something like this
return AlreadyExists()
which return 1001 status code. Can I implement such a way? if yes, How can I implement this? can someone please help me?
Upvotes: 1
Views: 12550
Reputation: 54087
You shouldn't go about inventing new HTTP status codes. I'd say that at best it violates the Principle of Least Astonishment.
How about returning a response with an HTTP status code of 400 (Bad Request), and an error object that contains your application's error code and message?
Alternatively, you could use the overload of CreateErrorResponse
that takes an exception argument.
Request.CreateErrorResponse(
HttpStatusCode.BadRequest,
new Exception("Email already exists.")
));
This results in the following JSON being returned from your endpoint:
{
"Message":"An error has occurred.",
"ExceptionMessage":"Email already exists.",
"ExceptionType":"System.Exception",
"StackTrace":null
}
Upvotes: 6
Reputation: 151586
When we use
return Unauthorized()
[...] In my case suppose email id already exists then I should return something like thisreturn AlreadyExists()
Unauthorized()
is just a method in the base controller, you can add methods to your own controller:
public IHttpActionResult AlreadyExists()
{
return new System.Web.Http.Results.ResponseMessageResult(
Request.CreateErrorResponse(
(HttpStatusCode)409,
new HttpError("Already exists")
)
);
}
If you want to reuse it, add your own controller base class and let your controllers inherit from that:
public class MyApiController : ApiController
{
public IHttpActionResult AlreadyExists()
{
return new System.Web.Http.Results.ResponseMessageResult(
Request.CreateErrorResponse(
(HttpStatusCode)409,
new HttpError("Already exists")
)
);
}
}
public class RegisterController : MyApiController
{
// ...
}
And like the others said, don't go invent your own HTTP status codes.
Upvotes: 5