Httpresponsemessage and Httpresponseexception are provided in the Web API to process the return message, Httpresponsemessage is used to return a request result message from the client, you can use the Httpresponsemessage a custom returned content, Httpresponseexception is used to return a client error message when an exception occurs, such as a 404 or 500 error.
In fact, with Httpresponsemessage can also return 404, 500 errors, why do you still need to use Httpresponseexception to return the error? A reference to this article raises the point that when a call to the Web API service occurs with a different error than expected, it is reasonable to abort the program to return the error message, and then use httpresponseexception for the wrong return. Httpresponsemessage means that when a client sends a job request and the Web API completes the job correctly, it can use Httpresponsemessage to return a 201 message, so Httpresponsemessage and Httpresponseexception in the use of the fundamental goal is different, with Httpresponsemessage to return an exception error will make the program structure is difficult to distinguish and not clear, then let us look at Httpresponsemessage and httpresponseexception operation mode. Www.it165.net
Httpresponsemessage
Httpresonsemessage is used to respond to messages and contain status codes and data content, such as the need to return a Httpresonsemessage instance to use the extended functionality Createresponse method of the Request, as follows
View Source print? 1. Public httpresponsemessage Deleteproductbyid (int id) 2. {3.//Do something ... 4. Return Request.createresponse (Httpstatuscode.ok); 5.}
Of course, you can also define the status code of the response and the data content, as follows view source print? 1. Public httpresponsemessage Deleteproductbyid (int id) 2. {3.//Do something ... 4. var response = Request.createresponse (Httpstatuscode.ok); 5. Response. StatusCode = Httpstatuscode.ok; 6. Response. Content = new Stringcontent ("Delete success!"); Response Content 7. return response; 8.}
If you need to respond to an enumeration object, you can use OBJECTCONTENT<T>, the following view source print? 1. Public Httpresponsemessage getallproducts () 2. {3. Httpresponsemessage response = new Httpresponsemessage (Httpstatuscode.ok); 4. Response. Content = new Objectcontent<ienumerable<product>> (5. New Productdao (). GetProducts (), 6. New Jsonmediatypeformatter ()); 7. Return response; 8.}
In addition, the Createresponse extension method also provides a createresponse<t> generic response method, as follows view source print