首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在netcore控制台应用程序中使用web服务器进行简单路由

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

Stack Overflow用户
提问于 2019-07-11 11:36:30
回答 1查看 4.4K关注 0票数 4

我在与kestrel一起工作时遇到了麻烦。

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

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

代码语言:javascript
复制
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)
        {
            // ????
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-11 16:30:20

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

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

代码语言:javascript
复制
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();
        }
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56981304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档