ASP.NET Core WebAPI Minimum Size / Bare-bones

Just for fun, earlier today one of my coworkers asked if I could try and make a small web interface that repeats requests using ASP.NET Core. I was able to get the WebAPI in about 70 lines of code. This is because ASP.NET Core is awesome! So this is what I ended up with so far.

Code

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace TinyWebApi
{
    class Program
    {
        static readonly IWebHost _host;
        static readonly string[] _urls = { "http://localhost:80" };

        static Program()
        {
            IConfiguration _configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
            _host = BuildHost(new WebHostBuilder(), _configuration, _urls);
        }

        static void Main(string[] args)
        {
            _host.Run();
        }

        static IWebHost BuildHost(
            IWebHostBuilder builder, IConfiguration configuration, params string[] urls)
        {
            return builder
                .UseKestrel(options =>
                {
                    options.NoDelay = true;
                })
                .UseConfiguration(configuration)
                .UseUrls(urls)
                .Configure(app =>
                {
                    app.Map("/echo", EchoHandler);
                })
                .Build();
        }

        static void EchoHandler(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                await context.Response.WriteAsync(
                    JsonConvert.SerializeObject(new
                    {
                        StatusCode = (string)context.Response.StatusCode.ToString(),
                        PathBase = (string)context.Request.PathBase.Value.Trim('/'),
                        Path = (string)context.Request.Path.Value.Trim('/'),
                        Method = (string)context.Request.Method,
                        Scheme = (string)context.Request.Scheme,
                        ContentType = (string)context.Request.ContentType,
                        ContentLength = (long?)context.Request.ContentLength,
                        QueryString = (string)context.Request.QueryString.ToString(),
                        Query = context.Request.Query
                            .ToDictionary(
                                _ => _.Key,
                                _ => _.Value,
                                StringComparer.OrdinalIgnoreCase)
                    })
                );
            });
        }
    }
}

      

(The above code works as expected and it didn't break.)


WebAPI

The WebAPI must trace the request using JSON.

Request example

http://localhost/echo?q=foo&q=bar

      

Sample response

{
  "StatusCode": "200",
  "PathBase": "echo",
  "Path": "",
  "Method": "GET",
  "Scheme": "http",
  "ContentType": null,
  "ContentLength": null,
  "QueryString": "?q=foo&q=bar",
  "Query": {
    "q": [
      "foo",
      "bar"
    ]
  }
}

      


My problem

I blew my colleague with only 70 lines of code to get the job done, but then when we looked at the file size it wasn't that impressive ...

At the moment, with all these dependencies, my WebAPI compiles to 54.3 MB.

I am stuck trying to figure out how to reduce disk space in this project. The packages I have installed are bundled with so many things that we really don't need and I keep having trouble finding the best resource or method to remove unnecessary references for this project.

.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
    <ApplicationIcon>Icon.ico</ApplicationIcon>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>

</Project>

      

Is there any quick way to find out what references I need for my code based project? I started earlier by clearing all the above dependencies and then tried adding them one at a time, but it turns out that it becomes an endless headache trying to resolve the missing links and seem to be permanently resolved. I'm sure someone has a solution for something like this, but I can't seem to find one. Thank.

+3


source to share


1 answer


What I did was just copy the code into a new .NET Core console project and fix the missing references. To figure out which ones you need to add for the missing APIs, I just did F12 on the missing element (Go to definition) in the working project with all references to see which assembly the API is defined in.

Since you are not using anything interesting here, so the template ASP.NET Core Web application

that comes with VS already uses all of these APIs, so you can use it as a "working project".

For example, it AddJsonFile

was defined in a package Microsoft.Extensions.Configuration.Json

.

So in the end I was left with



<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>

</Project>

      

Up to 2.41 MB added when published.

Let's say you probably don't want to do this in a larger project. This project only takes about a minute.

+4


source







All Articles