I'm trying to return a 304 Not Modified status code in my ASP.Net Core application when a file is accessed via my middleware.
I try setting the HTTP Status Code and sending the response back like so:
context.Response.StatusCode = 304;
await context.Response.WriteAsync("Not Modified");
But I get this exception:
System.InvalidOperationException occurred HResult=-2146233079
Message=Write to non-body 304 response.
Source=Microsoft.AspNetCore.Server.Kestrel StackTrace: at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.HandleNonBodyResponseWrite() at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.d__183.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at Adapt.REST.ServeStaticFilesMiddleware.d__8.MoveNext() in C:\AdaptSource\Xivic\Adapt.Services\ServeStaticFilesMiddleware.cs:line 113 InnerException:
So obviously I can't use WriteAsync or SendFileAsync because they both send a response that contains a body.
How do I send a 304 back to the client without a body?
Simply doing nothing after setting the status code causes the intended functionality.
context.Response.StatusCode = 304;
return;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With