DEV Community

Omo Agbagbara
Omo Agbagbara

Posted on

Returning Correct StatusCodes in Azure Function Apps

I was recently involved in working on some middleware which recieves requests from an asset management system , tranform the data and send it over to an on premise deployment of business management solution.

This middleware has to be implemented as a C# function app. One key feature of this middleware, was to use the guaranteed delivery pattern.

Implementing this as C# function app is quite a trivial which involves.

  1. Receive the request.
  2. Validate request, throw a validation error if neccessary and send response.
  3. Send the request to Service Bus and return an HTTP response

In C# function apps, it is possible to return a HTTP response and send the request to a Service Bus using a class

Image description

And this class can be used as follows

Image description

However when it comes to returning errors, I encountered a problem using

await response.WriteAsJsonAsync("Some Text");
Enter fullscreen mode Exit fullscreen mode

Using this statement results in the response status code always being 200 OK.
Gone are the days when developers would return a 200 OK status code regardless of the fact that an error has occurred. It is now a must to return the right status code when building APIs.

Code Segments to Trigger Errors

Returning Errors

Bad Request with 200 OK Status Code.

Bad Request with 200 OK status code

Internal ServerError with 200 OK Status Code

Internal Server Error with 200 OK status code

Solution

I found that the solution to this is to use

response.WriteString("Some String"); 
Enter fullscreen mode Exit fullscreen mode

and to set the following in the Program.cs

services.Configure<KestrelServerOptions>(options =>{
            options.AllowSynchronousIO  = true;
        });
Enter fullscreen mode Exit fullscreen mode

Updated Code

Image description

Status Codes Being Returned Correctly

Image description

Image description

This took me a while to find this solution, and I hope it saves you a lot of time and headache in trying to debug what the issue.

Top comments (0)