Home > OS >  Why do I get different status code depending on expressions order?
Why do I get different status code depending on expressions order?

Time:02-26

I'm using ASP.NET Core 3. This is the simple code of my endpoint:

await context.Response.WriteAsync("Not Found");
context.Response.StatusCode = StatusCodes.Status404NotFound;

I expected to get 400 status code, but I got 200. However, if I change the code strings order:

context.Response.StatusCode = StatusCodes.Status404NotFound;
await context.Response.WriteAsync("Not Found");

then I get 404 status code. Why does the status code value depend on the order of expressions?

CodePudding user response:

The WriteAsync method actually sends out the response, so in the 1st example you are sending the response with the default status code (i.e. 200), and then modifying the status code of the response variable which is then not used further

  • Related