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 datareturn Request.CreateResponse(HttpStatusCode.OK, data);}else{// Return error response indicating resource not foundreturn Request.CreateErrorResponse(HttpStatusCode.NotFound, "Resource not found.");}}catch (Exception ex){// Log the exception or handle it appropriately// Return error response indicating internal server errorreturn 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 sourceif (id == 1){return new { Id = 1, Name = "Example Data" };}else{return null;}}
}


