Web API Controller C# - How to Return Http Status Code

If you're working with a Web API controller in C#, it's important to understand how to return the correct HTTP status code for your responses. This can help ensure that your API is properly communicating with clients and handling errors correctly.

To return an HTTP status code from your Web API controller, you can use the built-in `HttpResponseMessage` class. This class allows you to set the status code, as well as any additional headers or content that you want to return.

Here's an example of how to return a `200 OK` status code from a Web API controller method:


public HttpResponseMessage Get()
{
    // Perform some logic to get the data you want to return
    var data = GetData();

    // Create a new HttpResponseMessage with the data and status code
    var response = Request.CreateResponse(HttpStatusCode.OK, data);

    // Return the response
    return response;
}

In this example, we first perform some logic to get the data that we want to return. We then create a new `HttpResponseMessage` object using the `Request.CreateResponse` method, passing in the `HttpStatusCode.OK` status code and the `data` object.

Finally, we return the `HttpResponseMessage` object from our controller method.

By using the `HttpResponseMessage` class in this way, you can easily return the correct HTTP status code for your Web API responses. This can help ensure that your API is properly communicating with clients and handling errors correctly.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information