|
In this article I will talk about handling exception in Web API using HTTPResponseException.
In most cases HTTP exceptions have status code of 500 which is Internal Server Error.
Using HTTPResponseException of Web API any status code which is specified in the constructor of the exception.
Let's write code.
Step 1: Download code from Consuming Web API using jQuery and inspecting Request and Response or you can create Web API application following the steps.
Step 2: Run DemoWebAPI.Html and enter 0 in the Customer Id and click on Search By Id.
If your code is running in debug mode you will get HTTPResponseException as shown below.
On continue executing the code you will get error Not found.
Now open IE developer tool by pressing F12. Go to Network tab and click on "Start Capturing" button. Now enter 0 in the Customer Id and click on Search by Id on the page again.
You see Response Headers you will see HTTP/1.1 404 Not Found
Check Response Body as well, you will notice it is blank with message "No data to view".
Step 3: Now open CustomerController.cs present in Controller folder and modify GetCustomerId like below.
public Customer GetCustomerById(int customerId) { var customer = customers.FirstOrDefault((p) => p.CustomerId == customerId); if (customer == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("{0} Customer Id does not exist.", customerId)), ReasonPhrase = "Customer ID Not Found" }; throw new HttpResponseException(resp); } return customer; }
Step 4: Now run DemoWebAPI.Html page again, open IE developer tool and navigte to Network and Start Capturing. Enter 0 to Customer Id text box and click on Search By ID button.
In the Response Body you will notice the message specified in the Content of HTTPResponseMessage.

Now check the Response header, it should have Custome ID Not Found which is specified in the ReasonPhrase but you will see Not Found.

Step 5: Right click on solution and click on properties. Go to Web tab and select Use Local IIS Web server radio button.

It might prompt you to create virtual directory.
Step 6: Now run the application again and now check Response Headers you will see Customer Not Found which is set in ReasonPhrase in code behind.

It made me believe that ReasonPhrase doesn't work in Cassini server. Not sure it is bug or it is intended to work like this.
This ends the article of HTTPResponseException in Web API of ASP.NET MVC 4.
|