[ASP.NET Core] Getting Started

时间:2023-03-09 03:26:29
[ASP.NET Core] Getting Started

前言

本篇文章介绍如何快速建立一个ASP.NET Core应用程序,为自己留个纪录也希望能帮助到有需要的开发人员。

环境

建立一个ASP.NET Core应用程序,首先要从官网下载SDK来建置.NET Core开发环境。

  • .NET Core官网

    [ASP.NET Core] Getting Started

  • 依照操作系统下载.NET Core SDK。

    [ASP.NET Core] Getting Started

    [ASP.NET Core] Getting Started

  • 安装.NET Core SDK

    [ASP.NET Core] Getting Started

  • .NET Core SDK安装完毕后,开启命令提示字符。输入「dotnet」,系统正常响应.NET Core的相关讯息,即完成.NET Core开发环境的建置。

    [ASP.NET Core] Getting Started

开发

  • 完成开发环境的建置后,就可以动手撰写ASP.NET Core应用程序。首先建立一个新的文件夹:「lab」。

    [ASP.NET Core] Getting Started

  • 接着在lab文件夹里,加入一个档案:「project.json」。并且修改档案内容为下列json格式内容,用以设定ASP.NET Core应用程序的项目参数。

    [ASP.NET Core] Getting Started

    {
    "version": "1.0.0-*",
    "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
    },
    "dependencies": {},
    "frameworks": {
    "netcoreapp1.0": {
    "dependencies": {
    "Microsoft.NETCore.App": {
    "type": "platform",
    "version": "1.0.0"
    },
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0"
    },
    "imports": "dnxcore50"
    }
    }
    }
  • 接着同样在lab文件夹里,加入一个档案:「Program.cs」。并且修改档案内容为下列C#程序代码内容,用以做为ASP.NET Core应用程序的范例程序。

    [ASP.NET Core] Getting Started

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http; namespace aspnetcoreapp
    {
    public class Program
    {
    public static void Main(string[] args)
    {
    // Build
    var host = new WebHostBuilder() // 设定Host内容的File根路径
    .UseContentRoot(Directory.GetCurrentDirectory()) // 设定启动参数
    .UseStartup<Startup>() // 开启Kestrel聆听HTTP
    .UseKestrel() // 设定聆听的URL
    .UseUrls("http://localhost:5000") // 建立Host
    .Build(); // Run
    try
    {
    // 启动Host
    host.Start(); // 等待关闭
    Console.WriteLine("Application started. Press any key to shut down.");
    Console.ReadKey();
    }
    finally
    {
    // 关闭Host
    host.Dispose();
    }
    }
    } public class Startup
    {
    // Methods
    public void Configure(IApplicationBuilder app)
    {
    // 挂载自定义的Middleware
    app.UseMiddleware<HelloWorldMiddleware>();
    }
    } public class HelloWorldMiddleware
    {
    // Fields
    private readonly RequestDelegate _next; // Constructors
    public HelloWorldMiddleware(RequestDelegate next)
    {
    _next = next;
    } // Methods
    public Task Invoke(HttpContext context)
    {
    // Response
    context.Response.WriteAsync("Hello World!"); // return
    return Task.CompletedTask;
    }
    }
    }
  • 再来开启命令提示字符,进入到上述的lab文件夹后。输入「dotnet restore」,用以初始化ASP.NET Core应用程序。

    [ASP.NET Core] Getting Started

  • 初始化ASP.NET Core应用程序后,接着输入「dotnet run」,用以编译并执行ASP.NET Core应用程序。

    [ASP.NET Core] Getting Started

  • 开发工作进行完毕之后,开发人员就可以开启浏览器,输入URL:「http://localhost:5000」,就可以在浏览器上,看到应用程序回传的"Hello World!"。

    [ASP.NET Core] Getting Started

参考