c# - 如何在没有日志记录和配置文件的情况下运行 ASP.NET Core Kestrel 服务器?
问题描述
我需要在现有的单体应用程序中注入一个 ASP.NET Core Web API 服务器。我的主要问题是关闭所有配置文件、环境配置、日志记录等等。
我只需要一个带有 MVC 路由的纯代码控制的 HTTP 服务器。
我怎样才能做到这一点?
解决方案
查看我的要点,以获得一个非常小的 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 处理程序。
推荐阅读
- r - 将带有嵌入列表的 json 解析为半长数据帧
- python - 在 Python 中解析 GC 日志
- python-3.x - Pyautogui 不会移动实际的鼠标指针
- c - 如何使用 pthread 在 c 中管理多个线程?
- sql-server - 试图将coldfusion中的内联查询转换为SQL存储过程
- javascript - GWT FocusPanel mousedownHandler 没有立即在 IE 11 的空白区域中调用
- python - ModuleNotFoundError:没有名为“PyPDF2”的模块
- neural-network - 在 2 个神经网络的组合中使用反向传播进行权重更新
- linux - 在 Linux 的目录中显示几行文件*
- rxjs - 相当于rxjs中循环中的循环