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.
- Receive the request.
- Validate request, throw a validation error if neccessary and send response.
- 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
And this class can be used as follows
However when it comes to returning errors, I encountered a problem using
await response.WriteAsJsonAsync("Some Text");
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
Bad Request with 200 OK Status Code.
Internal ServerError with 200 OK Status Code
Solution
I found that the solution to this is to use
response.WriteString("Some String");
and to set the following in the Program.cs
services.Configure<KestrelServerOptions>(options =>{
options.AllowSynchronousIO = true;
});
Updated Code
Status Codes Being Returned Correctly
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 (1)
Azure Function App with Unit Testing