HttpResponseException Was Unhandled By User Code In Web API

In order to reach a broad range of clients including the Browsers or mobile devices, the industry is moving towards using HTTP based Restful Services. ASP.NET Web API is an ideal platform to build Restful Services, using .NET Framework.

Exception handling is one of the most important things, which we use while creating any Application. If we try to throw an exception from an Action method within Web API, you may face the exception- "HttpResponseException was Unhandled by user code."
  1. public List<Employee> Get()  
  2.        {  
  3.            if(employees.Count==0)  
  4.            {  
  5.                var responseMessage = new HttpResponseMessage()  
  6.                {  
  7.                    Content = new StringContent("Please Enter Employee Id"),  
  8.                    ReasonPhrase = "Please Enter Employee Id",  
  9.                    StatusCode = HttpStatusCode.NoContent  
  10.   
  11.                };  
  12.                throw new HttpResponseException(responseMessage);  
  13.            }  
  14.            return  employees;  
  15.        }  
In the code snippet, given above, you will get an error in line number 12, when no employees are there in the list and we are trying to throw HTTPResponseException with the custom error message.

This is actually not an error, actually you are throwing an exception, which will go outside the user code and needs to be handled by the framework to generate HTTP response, which needs to be sent to the client. Thus, to solve this issue, we need to add an exception in Exceptions within debug menu of Visual Studio.

In Visual Studio 2015 select Debug => Windows => Exception Settings, the snapshot is given below-
 


In the Exception Settings, go to Common Language Runtime.

 
Right click on Common Language run time exceptions and click Add Exception. Enter the Exception Type as “System.Web.Http.HttpResponseException”. Right click on the newly added exception and click "Continue" when Unhanded in User Code. After adding these in Exception settings, you will not get this error. Instead, you will see the custom response message.