user9536240
user9536240

Reputation:

How to return HttpResponseException with error specificaton (invalid username or invalid password) to the frontend?

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

Answers (3)

Glen Thomas
Glen Thomas

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

Jesse Milam
Jesse Milam

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

Valentin
Valentin

Reputation: 5488

You can use HttpException and this constructor

throw new HttpException(400, "Invalid username")

Upvotes: 1

Related Questions