Search code examples
c#asp.net-apicontroller

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

Solution

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