1
votes

I'm self hosting a web app using Microsoft.Owin.Hosting.WebApp, but after making a HEAD request to the server, it throws a 500 error. When trying to pull a JSON file, the error changes to 504.

I've seen many solutions, but none applying to WebApp. If hosting with NancyFX, I could set AllowChunkedEncoding to false to make it work. But that doesn't seems like a good option.

Code snippet:

var options = new StartOptions("http://localhost:8080")
{
  ServerFactory = "Microsoft.Owin.Host.HttpListener"
};
WebApp.Start<Startup>(options);

Implementation of Startup:

  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      app.UseNancy();
    }
  }

Both calling the browser or using Fiddle causes a failure: enter image description here

I haven't added the Nancy Module implementation here because it's not where the problem should be fixed, as I also want to serve static content, but allowing HEAD request on them.

Does anyone knows how to serve HEAD verbs from a Self Hosted OWIN?

2

2 Answers

0
votes

I just ran into a very similar issue like this. I learned that HEAD method responses should be identical to GET responses but with no content.

Here's the relevant RFC: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Example I have for my self-hosted Web api app:

[HttpHead]
[HttpGet]
[ResponseType(typeof(string))]
public HttpResponseMessage LiveCheck(HttpRequestMessage request)
{
    HttpResponseMessage response;

    response =  request.CreateResponse(HttpStatusCode.OK);
    if (request.Method == HttpMethod.Get)
    {
        response.Content = new StringContent("OK", System.Text.Encoding.UTF8, "text/plain");
    }
    return response;
}
0
votes

I had a similar issue with a self-hosted SignalR app where HEAD requests caused an app crash and returned error code 500. The solution I found was to write a custom OWIN middleware layer to intercept HEAD requests and return code 200.

Create a new class in your project called HeadHandler.cs

using Microsoft.Owin;
using System.Threading.Tasks;

namespace YourProject
{
    public class HeadHandler : OwinMiddleware
    {
        public HeadHandler(OwinMiddleware next) : base(next)
        {
        }

        public override async Task Invoke(IOwinContext context)
        {
            if (context.Request.Method == "HEAD")
            {
                context.Response.StatusCode = 200;
            }
            else
            {
                await Next.Invoke(context);
            }
        }
    }
}

In your OWIN Startup class, add a line before mapping any other middleware to use the new HeadHandler middleware.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<HeadHandler>();
        //The rest of your original startup class goes here
        //app.UseWebApi()
        //app.UseSignalR();
    }
}