.NET 快速开始
本文档介绍从零开始手动将一个 .NET 应用容器化,并部署到腾讯云托管(CloudBase Run)。
第 1 步:编写基础应用
安装 .NET Core SDK 3.1。在 Console 中,使用 dotnet 命令新建一个空 Web 项目:
dotnet new web -o helloworld-csharp
cd helloworld-csharp
更新 Program.cs 中的 CreateHostBuilder 定义,侦听 80 端口:
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace helloworld_csharp
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
string port = "80";
string url = String.Concat("http://0.0.0.0:", port);
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseUrls(url);
});
}
}
}
将 Startup.cs 的内容更新为如下:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace helloworld_csharp
{
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)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!\n");
});
});
}
}
}
以上代码会创建一个基本的 Web 服务器,并监听 80 端口。