I’m testing my C# API endpoint and encountering a discrepancy between the status code I return in my controller and what I receive by using fetch. I have configured my C# controller to return a 400 Bad Request if a parameter value does not match the expected format. However, when I make a request with invalid parameters using fetch, response.status shows 422 Unprocessable Entity instead of 400.
Here’s the relevant code:
In my C# API, I’m checking if the category parameter is valid. If it’s not, I set up a ProblemDetails response with a 400 status code. When I fill in a false parameter, it does return the 400.
if (!string.IsNullOrEmpty(category) && category != "http://terminology.hl7.org/CodeSystem/observation-category|laboratory")
{
return UnprocessableEntity(new ProblemDetails
{
Title = "Ongeldige parameter",
Detail = "De enige toegestane waarde voor 'category' is 'http://terminology.hl7.org/CodeSystem/observation-category|laboratory'.",
Status = 400
});
}
I’m using fetch-api to make the request. This code snippet shows how I’m sending the request and logging the response status.
async def make_request(params):
response = await fetch('/api/request', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: document.getElementById('url').value,
params: params
})
})
data = await response.json()
print(response.status) # This shows 422 instead of 400
return {
'status': response.status,
'data': data
}
Why does the response.status in JavaScript show 422 instead of 400? Is this an issue with how UnprocessableEntity works in C# when setting a custom Status code, or could it be something specific to the fetch implementation in JS?