简体   繁体   English

最小的占用空间/裸机ASP.NET核心WebAPI

[英]Minimal Footprint / Bare-bones ASP.NET Core WebAPI

Just for fun, earlier today one of my colleagues asked if I could try and make a tiny-footprint WebAPI that echoed requests using ASP.NET Core. 只是为了好玩,今天早些时候我的一位同事问我是否可以尝试制作一个使用ASP.NET Core回应请求的小型WebAPI。 I was able to get the WebAPI done in about 70 lines of code. 我能够在大约70行代码中完成WebAPI。 All thanks to ASP.NET Core being amazing! 一切都归功于ASP.NET Core令人惊叹! So, this is what I ended up with so far. 所以,这就是我到目前为止的结果。

The 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 code above works as expected, and it's not broken.) (上面的代码按预期工作,并没有被破坏。)


The WebAPI WebAPI

The WebAPI is supposed to echo back the request with a JSON. WebAPI应该用JSON回显请求。

Example Request 示例请求

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

Example 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 away with just the 70+ lines of code to do the job, but then when we took a look at the file size it wasn't as impressive... 我只用70多行代码就把我的同事吹走了,但是当我们查看文件大小时,它并没有那么令人印象深刻......

At the moment with all these dependencies, my WebAPI is compiling to 54.3MB. 目前所有这些依赖项,我的WebAPI编译为54.3MB。

I am stuck with trying to figure out how to reduce the disk footprint of this project. 我一直在努力弄清楚如何减少这个项目的磁盘占用空间。 The packages I have installed are bundled up with so much stuff we don't really need and I keep running into trouble trying to find out the best resource or method to removing the unneeded references for this project. 我安装的软件包捆绑了很多我们并不真正需要的东西,并且我一直在努力寻找最佳资源或方法去除这个项目的不需要的引用。

The .csproj .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 for me to know what references my project needs based on the code provided? 根据提供的代码,我有什么快速的方法可以了解我的项目需要什么参考? I started earlier by wiping clear all the above dependencies and then trying to add them one by one, but it turns out to become a never ending headache of trying to solve missing references and it seems to take forever to solve. 我之前开始擦除清除所有上述依赖项,然后尝试逐个添加它们,但事实证明这是一个永无止境的尝试解决缺失引用的问题,似乎需要永远解决。 I'm sure someone out there has a solution for something like this, but I can't seem to find it. 我相信那里有人有这样的解决方案,但我似乎无法找到它。 Thanks. 谢谢。

What I did was just copy the code to a new .NET Core console project and resolved the missing references. 我所做的只是将代码复制到新的.NET Core控制台项目并解决了缺少的引用。 To figure out which ones you need to add for the missing APIs I just did F12 on the missing member (Go to definition) in the working project with all references to see in which assembly the API is defined. 为了找出你需要为缺失的API添加哪些,我只是在工作项目中缺少的成员(转到定义)上做了F12,所有引用都参见了定义API的程序集。

Since you're not using anything fancy here, so the ASP.NET Core Web application template shipped in VS already uses all of these APIs, so you could use that as the 'working project'. 由于您没有使用任何花哨的东西,因此VS中提供的ASP.NET Core Web application模板已经使用了所有这些API,因此您可以将其用作“工作项目”。

The AddJsonFile for example was defined in Microsoft.Extensions.Configuration.Json package. 例如, AddJsonFile是在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>

When published it added up to 2.41MB. 发布时,它增加了2.41MB。

Granted you probably wouldn't want to do this on a bigger project. 当然,您可能不希望在更大的项目上执行此操作。 On this project in only takes a minute or so. 在这个项目上只需要一分钟左右。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM