How to fix top-level-statement error in creating http3 sample project

195 Views Asked by At

I'm creating a sample C# environment for http3 in .net 6 I'm following this blog but I'm getting this error:

Error CS8802 Only one compilation unit can have top-level statements.

Here is my Program.cs code which in Server project it is showing the error on the var builder line:

using Microsoft.AspNetCore.Server.Kestrel.Core;
// This namespace contains the IPAddress type
using System.Net;

var builder = WebApplication.CreateBuilder(args);

// Configure kestrel (the web server)
builder.WebHost.ConfigureKestrel((context, options) =>
{
    // Listen on port 5001
    options.Listen(IPAddress.Any, 5001, listenOptions =>
    {
        // Serve traffic using HTTP/2 or HTTP/3
        listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
        // Use HTTPS
        listenOptions.UseHttps();
    });
});

var app = builder.Build();


// Configure the root to also accept GET requests
app.MapGet("/", () => $"The time on the server is {DateTime.Now}");

app.Run();

Here is my Program.cs code which in Client project:

using System.Net;

// Create a handler to turn off SSL validation
//var EndPoint = "https://192.168.0.1/api";
var httpClientHandler = new HttpClientHandler();

httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
{
    return true;
};
//HttpClient = new HttpClient(httpClientHandler) { };

// Create a new HttpClient and wire it to our handler
var client = new HttpClient(httpClientHandler)
{
    //BaseAddress = new Uri(EndPoint),
    // Specify that requests should be for HTTP/3
    DefaultRequestVersion = HttpVersion.Version30,
    DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact
};


// Get our response
var response = await client.GetAsync("https://localhost:5001/");
// Read the body
var body = await response.Content.ReadAsStringAsync();


// Print the relevant headers to verify our results
Console.WriteLine($"HTTP Version: {response.Version}");
Console.WriteLine($"Status: {response.StatusCode}");
Console.WriteLine($"Body: {body}");

What should I do in this scenario?

0

There are 0 best solutions below