在 netcore 控制台应用程序中使用 Web 服务器进行简单路由

use*_*989 4 c# kestrel-http-server asp.net-core

我无法让路由与 kestrel 一起工作。

我找不到关于如何在 netcore 控制台应用程序中实现这一点的任何好的教程。

我想构建一个简单的 Web 服务器,它将有 2-3 个我可以访问的端点。

public class WebServer
{
    public static void Init()
    {
        IWebHostBuilder builder = CreateWebHostBuilder(null);
        IWebHost host = builder.Build();
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .Build();

        return WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5000")
            .UseConfiguration(config)
            .UseStartup<Startup>();
    }

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting();
            // ????
        }

        public void Configure(IApplicationBuilder app)
        {
            // ????
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

文件 > 新建项目 > 空的 ASP.NET Core 应用程序。

为了在控制台应用程序中运行它,请确保在 Visual Studio 的“运行”下拉列表中选择项目名称。

在此处输入图片说明

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace WebApplication7
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

    public class MyEndpoint : Controller
    {
        [Route("")]
        public IActionResult Get()
        {
            return new OkResult();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)