Skip to content

Commit

Permalink
Merge pull request #4 from AKlaus/bugfix/#3
Browse files Browse the repository at this point in the history
Return HTTP 405 `Forbidden POST` on POST requests to /index.html
  • Loading branch information
AKlaus authored Jan 16, 2024
2 parents 182bc06 + 60e0147 commit c13b2e0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
17 changes: 16 additions & 1 deletion Configuration/UseSpaWithNoCache.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Net.Http.Headers;

Expand Down Expand Up @@ -35,12 +36,26 @@ public static IApplicationBuilder UseSpaWithNoCache(this IApplicationBuilder app
}
}
});

// Prevent HTTP 500 response on non-GET requests (e.g. POST, OPTIONS) to non-API end-points
// See https://github.com/dotnet/aspnetcore/issues/5223#issuecomment-1135817359
app.Use(async (context, next) =>
{
if (context.GetEndpoint() == null && !HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
{
context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
await context.Response.WriteAsync($"Forbidden {context.Request.Method}");
}
else
await next();
}
);

// Does 3 things:
// - Redirects all requests to the default page;
// - Serves 'index.html'
// - Tries to configure static files serving (falls back to UseSpaStaticFiles() and serving them from 'wwwroot')
app.UseSpa(c => c.Options.DefaultPageStaticFileOptions = new StaticFileOptions { OnPrepareResponse = SetNoCaching});
app.UseSpa(c => c.Options.DefaultPageStaticFileOptions = new StaticFileOptions { OnPrepareResponse = SetNoCaching });

// Note: There's no need in calling UseDefaultFiles() prior to UseStaticFiles() as the docs insist (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files#serve-default-documents),
// because UseSpa() extension does the same and allows to setup caching policies
Expand Down
2 changes: 1 addition & 1 deletion MinimalApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// Configure the HTTP request pipeline
var app = builder.Build();

if (isLocal)
if (!isLocal)
{
// CORS if needed for development only
// app.UseCors();
Expand Down

0 comments on commit c13b2e0

Please sign in to comment.