Saturday, May 6, 2017

Make a ghetto endpoint in a .NET Core app!

I need to figure out how to make controllers in a .NET Core app. In the short term however...

  1. Get Visual Studio 2017!
  2. Install .NET Core. Per this it's the ".NET Core cross-platform development" workload. Everything is modular in Visual Studio 2017 with containers of funtionality optional opt-ins.
  3. Under Visual C# Templates there is a .NET Core subsection with a "ASP.NET Core Web Application (.NET Core)" option nested further inside when you create a new project assuming you got on the other side of the first two steps above alright. Make a new project of this ilk.
  4. Just use the "Empty" template. It will make mostly nude app with two C# classes. One is Program.cs which is the front door to the application. It looks like...
    using System.IO;
    using Microsoft.AspNetCore.Hosting;
    namespace Whatever
    {
       public class Program
       {
          public static void Main(string[] args)
          {
             var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
             host.Run();
          }
       }
    }

    ...and can mostly just be left alone, truth be told. The other file is Startup.cs which Program.cs designates as the outmost Russian doll in the middleware paradigm. In our case there are no other Russian dolls. I'll get to Program.cs later on.
  5. Run Install-Package Microsoft.AspNetCore.Cors at the NuGet console to add Cors so that we may open up our endpoint to the world beyond our app.
  6. Open PowerShell and enter the dotnet restore command at the folder holding the .sln file. This will restore any missing NuGet dependencies in what is sort of like an npm install fashion. We may not really need it in this immediate case, but this is a good practice before...
  7. Running the dotnet run command. Do note .UseKestrel() in Program.cs which means we will be using the Kestrel web server and not IIS Express! You will want to run this command in the same folder that Program.cs lives in. The web server will run until you press Ctrl-C and it should tell you what port the app is running at at localhost. http://localhost:5000 probably has your app and if you look at it in a browser you will probably see "Hello World" spat back to you from the Startup.cs default placeholder code.

 
 

Alright we are going to leave the ability for the application to tell us "Hello World" alone, but we are also going to add a second endpoint at http://localhost:5000/whatever which will give us a string of pipe-separated metasyntactic variables. Revamp Startup.cs like so:

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Whatever
{
   public class Startup
   {
      public void ConfigureServices(IServiceCollection services)
      {
         services.AddCors();
      }
      
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
         app.UseCors(builder =>
         {
            builder.AllowAnyHeader();
            builder.AllowAnyMethod();
            builder.AllowAnyOrigin();
         });
         app.Map("/whatever", HandleWhateverRoute);
         app.Run(async (context) =>
         {
            await context.Response.WriteAsync("Hello World!");
         });
      }
      
      private static void HandleWhateverRoute(IApplicationBuilder app)
      {
         var metasyntactic = new List<string>()
         {
            "foo",
            "bar",
            "baz",
            "qux"
         };
         var flattening = metasyntactic.Aggregate("|", (x, y) => x + y + "|");
         app.Run(async context => {
            await context.Response.WriteAsync(flattening);
         });
      }
   }
}

 
 

You should be able to see the |foo|bar|baz|qux| copy if you run the app and hit the endpoint. With Cors opened up another app could scrape this content in and break up the string based on the pipe symbols. This is weak, I know. It's a start. :)

No comments:

Post a Comment