Search code examples
c#httpasp.net-corekestrel-http-server

Kestrel returns empty response to HttpContext


I have set up a basic Kestrel instance in a Console Application like so:

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace HiStackOverflow
{
    class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseStartup<Startup>()
                .UseUrls("http://localhost:5001")
                .Configure(c =>
                    c.Run(a =>
                        {
                            Console.WriteLine("writing response");
                            return a.Response.WriteAsync("Hello world");
                        }
                    )
                )
                .Build();
            
            host.Start();
            
            Console.WriteLine("Host setup finished, continuing with program.");
            Console.ReadLine();
        }
    }
}

If I then navigate to http://localhost:5001/ in a web browser, the application runs the code to send a response (breakpoints are hit, and "writing response" is written to the console), however, I receive an empty response. Specifically ERR_EMPTY_RESPONSE in Chrome.

If I try to view the response in Postman I receive a "Socket hang up" error.

I cannot figure out why this is happening. This is the first time I'm attempting to set up a Kestrel instance from scratch, so if anybody could shed some light on the problem it would be a huge help. Thanks!


Solution

  • You're calling UseStartup<Startup>(), but you didn't post the Startup class code. If I remove that from your example it works fine.

    Additionaly you're calling HttpContext.Response.WriteAsync() which returns a Task (it's asynchronous).
    You should await it like this:

    .Configure(c =>
        c.Run(async a =>
            {
                Console.WriteLine("writing response");
                await a.Response.WriteAsync("Hello world");
            }
        )
    )