Reputation:
How do i return Bad Request exception with text like "Invalid username" to frontend in ApiController. My code:
public class FrontEndController : ApiController
{
public string Test(string value)
{
if(!isValid(value))
//how do i throw exception with its code (400 in this case) and message ("Invalid username")
}
}
Upvotes: 1
Views: 221
Reputation: 10744
There is a BadRequest method on ApiController:
return BadRequest("Invalid username");
This creates an ErrorMessageResult (400 Bad Request) with the specified error message.
Upvotes: 1
Reputation: 66
You can change your method return type to HttpResponseMessage
and use the built in API functionality to return the error message you'd like.
public class FrontEndController : ApiController
{
public HttpResponseMessage Test(string value)
{
if(!isValid(value))
{
//Generate error response here
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Username");
}
}
}
Upvotes: 0
Reputation: 5488
You can use HttpException
and this constructor
throw new HttpException(400, "Invalid username")
Upvotes: 1