Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a Status Code 304 in Middleware

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?

like image 880
The Pademelon Avatar asked Feb 05 '23 09:02

The Pademelon


1 Answers

Simply doing nothing after setting the status code causes the intended functionality.

context.Response.StatusCode = 304;
return;
like image 93
The Pademelon Avatar answered Feb 08 '23 15:02

The Pademelon