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

时间:2023-03-09 08:51:25
NetCore的控制台应用中搭建WebServer的方法

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

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

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

二、新建一个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();
} }
}

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

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

相关文章