var responseMessage = new HttpResponseMessage>(errors, HttpStatusCode.BadRequest);throw new HttpResponseException(responseMessage);
Below is the sample code to show how to set error result in Web API –HttpResponseMessage myresponse = new HttpResponseMessage(HttpStatusCode.Unauthorized); myresponse.RequestMessage = Request; myresponse.ReasonPhrase = ReasonPhrase;
In ASP.NET Web API, you can return error responses using the HttpResponseMessage class along with appropriate HTTP status codes to indicate the nature of the error. Here’s how you can set the error result in a Web API controller:using System.Net;using System.Net.Http;using System.Web.Http;
public class ValuesController : ApiController{ public HttpResponseMessage Get(int id) { try { // Logic to retrieve data based on id // For example, fetching data from a database var data = GetDataById(id);
if (data != null) { // Return success response with data return Request.CreateResponse(HttpStatusCode.OK, data); } else { // Return error response indicating resource not found return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Resource not found."); } } catch (Exception ex) { // Log the exception or handle it appropriately // Return error response indicating internal server error return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An unexpected error occurred."); }}private object GetDataById(int id){ // Dummy method to simulate fetching data by id // In a real application, this would fetch data from a database or other source if (id == 1) { return new { Id = 1, Name = "Example Data" }; } else { return null; }}
if (data != null)
{
// Return success response with data
return Request.CreateResponse(HttpStatusCode.OK, data);
}
else
// Return error response indicating resource not found
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Resource not found.");
catch (Exception ex)
// Log the exception or handle it appropriately
// Return error response indicating internal server error
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An unexpected error occurred.");
private object GetDataById(int id)
// Dummy method to simulate fetching data by id
// In a real application, this would fetch data from a database or other source
if (id == 1)
return new { Id = 1, Name = "Example Data" };
return null;
You can return any of the status type bsaed on the error :400 Bad Request401 Unauthorized403 Forbidden404 Not Found500 Internal Server Error