欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

NetCore的控制台应用中搭建WebServer的方法

一、新建NetCore控制台项目,并引入下列Nuget包:

  Microsoft.AspNetCore.StaticFiles、Microsoft.AspNetCore.Http、Microsoft.AspNetCore.Http.Abstractions、Microsoft.AspNetCore.Server.Kestrel

  

二、新建一个Startup类。

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

namespace NetCoreWebServerDemo
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var staticfile = new StaticFileOptions();
            staticfile.FileProvider = new PhysicalFileProvider(@"D:\");
            app.UseStaticFiles(staticfile);
            app.Run(new Microsoft.AspNetCore.Http.RequestDelegate(HttpRequestHandler));
        }

        private async Task HttpRequestHandler(HttpContext context)
        {
            await context.Response.WriteAsync("hello  here is songxingzhu prov.");
        }
    }
}

 

三、在Main函数中这样写:

using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace NetCoreWebServerDemo
{
    class Program
    {
        public static void Main(string[] args)
        {
            var host =
                new WebHostBuilder().
                UseKestrel().
                UseContentRoot(Directory.GetCurrentDirectory()).
                UseUrls("http://0.0.0.0:8080").
                UseStartup<Startup>().Build();

            host.Run();
        }

      
    }
}

 

四、启动运行。如图,一个简单的文件服务器就搭好了。

 

posted @ 2017-05-05 17:16  宋兴柱  阅读(3181)  评论(0编辑  收藏  举报