首页 > 解决方案 > 如何在没有日志记录和配置文件的情况下运行 ASP.NET Core Kestrel 服务器?

问题描述

我需要在现有的单体应用程序中注入一个 ASP.NET Core Web API 服务器。我的主要问题是关闭所有配置文件、环境配置、日志记录等等。

我只需要一个带有 MVC 路由的纯代码控制的 HTTP 服务器。

我怎样才能做到这一点?

标签: c#asp.net-coremodel-view-controllerkestrel-http-server

解决方案


查看我的要点,以获得一个非常小的 kestrel instance/asp.net web 应用程序。

要启用 MVC,请将其更改如下:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace WebApp 
{
  public class Program
  {
    public static async Task<int> Main(string[] args) {
      try {
        var host = new WebHostBuilder()
          .UseKestrel()
          .UseUrls("http://localhost:5000/;https://localhost:5001")
          .ConfigureServices(_configureServices)
          .Configure(_configure)
          .Build();

        await host.RunAsync();

        return 0;
      }
      catch {
        return -1;
      }
    }

    static Action<IServiceCollection> _configureServices = (services) => {
         services.AddControllersWithViews();
    };

    static Action<IApplicationBuilder> _configure = app => {
      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
          endpoints.MapControllers();
      });

      app.Run((ctx) => ctx.Response.WriteAsync("Page not found."));
    };
  }
}

这也利用了入口点的新异步功能Main(string[] args),将服务器启动包装在 try/catch 中,并注册了一个 catch-all not found 处理程序。


推荐阅读