4
Reply

How to set the Error Result in Web API?

Suresh Kumar

Suresh Kumar

7y
7.1k
2
Reply

    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);

    1. if (data != null)
    2. {
    3. // Return success response with data
    4. return Request.CreateResponse(HttpStatusCode.OK, data);
    5. }
    6. else
    7. {
    8. // Return error response indicating resource not found
    9. return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Resource not found.");
    10. }
    11. }
    12. catch (Exception ex)
    13. {
    14. // Log the exception or handle it appropriately
    15. // Return error response indicating internal server error
    16. return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An unexpected error occurred.");
    17. }
    18. }
    19. private object GetDataById(int id)
    20. {
    21. // Dummy method to simulate fetching data by id
    22. // In a real application, this would fetch data from a database or other source
    23. if (id == 1)
    24. {
    25. return new { Id = 1, Name = "Example Data" };
    26. }
    27. else
    28. {
    29. return null;
    30. }
    31. }

    }

    You can return any of the status type bsaed on the error :
    400 Bad Request
    401 Unauthorized
    403 Forbidden
    404 Not Found
    500 Internal Server Error