create a console application that exposes a rest api in csharp

To create a console application that exposes a REST API, follow these steps:

  1. Create a new console application project in Visual Studio.
  2. Add the Microsoft.AspNetCore package to your project through NuGet.
  3. In your Program.cs file, put the following code to set up a simple REST endpoint:
main.cs
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

class Program
{
    static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureServices(services => services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>())
            .Configure(app =>
            {
                app.Run(async context =>
                {
                    if (context.Request.Path == "/api/status")
                    {
                        context.Response.StatusCode = 200;
                        await context.Response.WriteAsync("OK");
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                    }
                });
            });
}
1024 chars
33 lines
  1. Run the console application.
  2. Visit http://localhost:5000/api/status in a web browser, and you should see OK.

This is just a starting point; you would need to add additional routing and functionality to the app to make it useful as an actual API. Additionally, you would need to host this app somewhere accessible, like on a cloud provider or dedicated server.

gistlibby LogSnag