Skip to content

Commit

Permalink
Correctly handle HEAD requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
nopara73 committed Oct 28, 2018
1 parent 70c81c1 commit a8b3806
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
55 changes: 55 additions & 0 deletions WalletWasabi.Backend/Middlewares/HeadMethodMiddleware.cs
@@ -0,0 +1,55 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WalletWasabi.Backend.Middlewares
{
/// <summary>
/// https://www.tpeczek.com/2017/10/exploring-head-method-behavior-in.html
/// https://github.com/tpeczek/Demo.AspNetCore.Mvc.CosmosDB/blob/master/Demo.AspNetCore.Mvc.CosmosDB/Middlewares/HeadMethodMiddleware.cs
/// </summary>
public class HeadMethodMiddleware
{
#region Fields

private readonly RequestDelegate _next;

#endregion Fields

#region Constructor

public HeadMethodMiddleware(RequestDelegate next)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
}

#endregion Constructor

#region Methods

public async Task InvokeAsync(HttpContext context)
{
bool methodSwitched = false;

if (HttpMethods.IsHead(context.Request.Method))
{
methodSwitched = true;

context.Request.Method = HttpMethods.Get;
context.Response.Body = Stream.Null;
}

await _next(context);

if (methodSwitched)
{
context.Request.Method = HttpMethods.Head;
}
}

#endregion Methods
}
}
6 changes: 6 additions & 0 deletions WalletWasabi.Backend/Startup.cs
Expand Up @@ -11,6 +11,7 @@
using WalletWasabi.Logging;
using WalletWasabi.Interfaces;
using Microsoft.AspNetCore.HttpOverrides;
using WalletWasabi.Backend.Middlewares;

namespace WalletWasabi.Backend
{
Expand Down Expand Up @@ -58,6 +59,11 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
c.SwaggerEndpoint("/swagger/v2/swagger.json", "Wasabi Wallet API V2");
});

// So to correctly handle HEAD requests.
// https://www.tpeczek.com/2017/10/exploring-head-method-behavior-in.html
// https://github.com/tpeczek/Demo.AspNetCore.Mvc.CosmosDB/blob/master/Demo.AspNetCore.Mvc.CosmosDB/Middlewares/HeadMethodMiddleware.cs
app.UseMiddleware<HeadMethodMiddleware>();

app.UseMvc();

var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
Expand Down

0 comments on commit a8b3806

Please sign in to comment.