Fork me on GitHub

.NET Core系列 : 1、.NET Core 环境搭建和命令行CLI入门

2016年6月27日.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布,社区里涌现了很多文章,我也计划写个系列文章,原因是.NET Core的入门门槛相当高,很有必要写个深入浅出的系列文章,本节内容帮助你入门。我将可能用Windows做开发环境,也可能用Linux/Mac,但是所有的dotnet CLI命令都是跨平台的,我们在windows/Linux/mac平台上开发跨平台的应用。

 

安装.NET Core

.NET Core 包括.NET Core Runtime 和 .NET Core SDK:

  1. .NET Core = 应用运行依赖的 .NET Core Runtime
  2. .NET Core SDK = 使用.NET Core开发应用.NET Core Runtime 和 SDK+CLI(Software Development Kit/Command Line Interface) 工具

下载地址请到dotnet官方网站dot.net (dot dot net),非常的好记,这个网站也是你入门学.NET Core的入口网站,记住这是个必须要去网站。.NET Core 下载的具体地址:https://www.microsoft.com/net/download#core,这里还列出了注意事项:

  1. 虽然.NET Core Runtime 和基础库已经1.0 RTM,但是开发工具链(.NET Core CLI,Visual studio 和Visual Studio Code) 还是预览版,具体可以参看https://blogs.msdn.microsoft.com/dotnet/2016/05/06/net-core-rc2-improvements-schedule-and-roadmap/
  2. 在Windows Servers上部署应用 ,可以单独安装ASP.NET Core Module for IIS 而不需要安装.NET Core runtime,可以通过命令行DotNetCore.1.0.0-WindowsHosting.exe OPT_INSTALL_REDIST=0
  3. Mac 系统的最低要求是macOS 10.11 (El Capitan)
  4. .NET Core 在Red Hat 系列服务器上支持的要 RHEL 7 Server,包括CentOS 7 以上,具体参看 https://access.redhat.com/documentation/en/dot-net-core/
  5. .NET Core 在Ubuntu上面的支持 需要 Ubuntu 14.04 LTS 和  Ubuntu 16.04 LTS
  6. 如果之前安装了.NET Core的beta,rc1,rc2的版本,在安装之前需要把他们卸载掉,具体参见 stack overflow 的文章。

.NET Core 的具体安装方法可以参看文章 .Net Core 系列:1、环境搭建

 

dotnet Command Line Interface(CLI)

.NET Core 的dotnet 命令行接口(CLI)非常重要,是我们开发,运营都要使用的一套工具,Microsoft 为我们提供了这个命令行工具以供我们在开发程序中使用,它主要用来进行对代码的编译、NuGet 包的管理、程序的运行、测试等等。简单的说 :当一个新人坐在座位上开始学习node, python, ruby, golang 或者其它任何东西时,对于绝大多数人来说,按照他们的经验就应该如此。使用.NET应当被看做是一件简单的不能再简单的事了。学习并且使用.NET 的伙伴们有着在Go或者Ruby上有相同的经验。这篇文章 .NET Core dotnet 命令大全 介绍了命令行的使用方法,dotnet run 命令介绍 更详细的介绍了dotnet run命令。练习例子可以用文章 通过几个Hello World感受.NET Core全新的开发体验

 

我们就来通过一个Hello World例子来学习下dotnet 命令行,我们安装好.NET Core 1.0,就可以做下面的事情了:

>dotnet new
>dotnet restore
>dotnet run

想象着和我一块儿,当你把这个和在Mac, Windows, Linux上运行的 Visual Studio代码相比较时,那么你已经获得了一个非常精彩的故事。可以很容易的在很多地方运行开源的.NET 代码。

下面是一段比较长的的代码,创建一个控制台应用,只要在顶部输入“dotnet”,就可以得到很多能用的东西。

[root@Mono helloworld]# dotnet

Microsoft .NET Core Shared Framework Host

  Version  : 1.0.1
  Build    : cee57bf6c981237d80aa1631cfe83cb9ba329f12

Usage: dotnet [common-options] [[options] path-to-application]

Common Options:
  --help                           Display .NET Core Shared Framework Host help.
  --version                        Display .NET Core Shared Framework Host version.

Options:
  --fx-version <version>           Version of the installed Shared Framework to use to run the application.
  --additionalprobingpath <path>   Path containing probing policy and assemblies to probe for.

Path to Application:
  The path to a .NET Core managed application, dll or exe file to execute.

If you are debugging the Shared Framework Host, set 'COREHOST_TRACE' to '1' in your environment.

To get started on developing applications for .NET Core, install .NET SDK from:
  http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409

[root@Mono ~]# mkdir helloworld
[root@Mono ~]# cd helloworld
[root@Mono helloworld]# dotnet new
Created new C# project in /root/helloworld.
[root@Mono helloworld]# ls
Program.cs  project.json
[root@Mono helloworld]# vi Program.cs
[root@Mono helloworld]# dotnet restore
log  : Restoring packages for /root/helloworld/project.json...
log  : Writing lock file to disk. Path: /root/helloworld/project.lock.json
log  : /root/helloworld/project.json
log  : Restore completed in 2277ms.
[root@Mono helloworld]# dotnet run
Project helloworld (.NETCoreApp,Version=v1.0) will be compiled because expected outputs are missing
Compiling helloworld for .NETCoreApp,Version=v1.0

Compilation succeeded.
    0 Warning(s)
    0 Error(s)

Time elapsed 00:00:03.0002808


Hello World!
[root@Mono helloworld]#

通过上面这几个基本命令就把我们的.NET Core 应用运行起来了。


 

dotnet new

new 命令用于创建.NET项目或者是应用


[root@Mono ~]# dotnet new --help
.NET Initializer

Usage: dotnet new [options]

Options:
  -h|--help             Show help information
  -l|--lang <LANGUAGE>  Language of project [C#|F#]
  -t|--type <TYPE>      Type of project

可以用这个命令创建几个不同类型的的应用类型,支持C#和F#,C#语言支持的项目类型如下:

  • Console
  • Web
  • Library
  • xUnit Test

 

dotnet restore

restore命令使用NuGet还原在项目文件project.json 中定义的依赖关系和项目特定的工具。


[root@Mono ~]# dotnet restore --help


Usage: nuget3 restore [arguments] [options]

Arguments:
  [root]  List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search fo                                                          r project.json files.

Options:
  -h|--help                       Show help information
  --force-english-output          Forces the application to run using an invariant, English-based culture.
  -s|--source <source>            Specifies a NuGet package source to use during  the restore.
  --packages <packagesDirectory>  Directory to install packages in.
  --disable-parallel              Disables restoring multiple projects in parallel.
  -f|--fallbacksource <FEED>      A list of packages sources to use as a fallback.
  --configfile <file>             The NuGet configuration file to use.
  --no-cache                      Do not cache packages and http requests.
  --infer-runtimes                Temporary option to allow NuGet to infer RIDs  for legacy repositories
  -v|--verbosity <verbosity>      The verbosity of logging to use. Allowed values: Debug, Verbose, Information, Minimal, Warning, Error.
  --ignore-failed-sources         Only warning failed sources if there are packages meeting version requirement
[root@Mono ~]#

正如你可以看到从"用法:"上面的一行,还原命令只调用到 nuget3 可执行程序,通常您不需要修改这些选项,如果您使用的自定义软件包源,要么因为您正在使用预发布版本的 Microsoft 库或您的组织使用其自己的软件包源,您可能需要指定使用-s 参数的软件包源。

运行 dotnet 还原生成一个锁文件 (project.json.lock),其中包括有关所有被恢复的软件包的详细的信息。

 

dotnet build

build命令会把项目和他所依赖的项目编译成一个二进制文件,默认情况下二进制文件是Intermediate Language (IL) 和.dll 为文件扩展名。编译过程依赖于已经存在锁文件(project.json.lock),这是restore命令生成的。

为了生成一个可执行的应用程序,您需要确保该项目配置的编译选项设置应用的入口点︰

 

 "buildOptions": {
    "emitEntryPoint": true
  },
运行命令可以看到使用方法: 
> dotnet build --help
.NET Builder

Usage: dotnet build [arguments] [options]

Arguments:
<PROJECT>  The project to compile, defaults to the current directory. Can be one or multiple paths to project.json, project directory or globbing patter that matches project.json files

Options:
-h|--help                           Show help information
-o|--output <OUTPUT_DIR>            Directory in which to place outputs
-b|--build-base-path <OUTPUT_DIR>   Directory in which to place temporary outputs
-f|--framework <FRAMEWORK>          Compile a specific framework
-r|--runtime <RUNTIME_IDENTIFIER>   Produce runtime-specific assets for the specified runtime
-c|--configuration <CONFIGURATION>  Configuration under which to build
--version-suffix <VERSION_SUFFIX>   Defines what `*` should be replaced with in version field in project.json
--build-profile                     Set this flag to print the incremental safety checks that prevent incremental compilation
--no-incremental                    Set this flag to turn off incremental build
--no-dependencies                   Set this flag to ignore project to project references and only build the root project

你可以使用-f 选项来指定你想要编译为一个特定框架。这一框架必须在项目文件中定义。-C 选项允许您指定要使用的配置。它将默认为Debug,但您可以指定为Release。

 

dotnet run

大多数情况下,你都是跳过上面的restore,build,直接使用dotnet run命令来运行程序,无论是否修改了应用程序,都是重新编译生成应用并运行。

> dotnet run --help
.NET Run Command
Usage: dotnet run [options] [[--] <arg>...]]

Options:
-h|--help           Show help information
-f|--framework      Compile a specific framework
-c|--configuration  Configuration under which to build
-p|--project        The path to the project to run (defaults to the current directory). Can be a path to a project.json or a project directory
dotnet run 命令介绍 更详细的介绍了dotnet run命令

-f, --framework

使用提供的 framework 来运行,这个 framework 就是对应project.json文件中的 frameworks 节点

-c, --configuration [Debug|Release]

配置使用的环境是 Debug 还是 Release,默认为 Debug 模式。

-p, --project [PATH]

指定要运行的项目,它可以是project.json的文件路径,可以是包含project.json的路径,如果没有指定,默认是当前路径。

 

dotnet [assemblyname]

可以用dotnet命令运行已经编译好的应用,把应用路径作为参数传递给dotnet命令

 

> dotnet .\bin\Debug\netcoreapp1.0\helloworld.dll
Hello World!

 

dotnet pack

pack命令编译项目并生成NuGet包,该操作会生成两个NuGet程序包:

  • 一个包括已编译代码的程序集文件
  • 一个包括调试符号和已编译代码的程序集文件

项目依赖的NuGet项目添加到生成nuspec文件中,默认情况不打包项目之间的引用关系,但可以通过更改项目的相关性类型。

 

dotnet publish

发布命令会编译应用程序并读取项目文件,然后将结果集的文件发布到一个目录。生成目录的内容将取决于项目的类型,但可以包括一个跨平台的 IL 应用程序和他依赖项,这就是通常用的Portable部署方式,应用程序共享.NET Core运行时环境与程序集依赖,部署的目标机器上需要事先安装.NET Core SDK,然后用dotnet命令运行程序。或者是每个本机平台的子文件夹或自包含的应用程序,其中包括目标平台的运行时,这就是Self-contained部署方式。Self-contained部署方式就是每个应用程序自带.NET Core运行时环境与程序集依赖,部署的目标机器不需要安装.NET Core SDK,将应用程序文件夹拷贝过来就能运行。具体参考文档参考文档 .NET Core Application Deployment 

 

默认的project.json编译出来的应用没有包括跨平台,需要修改project.json文件,需要在 project.json 加入 runtimes 节点 注释掉 "type": "platform"

 

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {"hwapp":"1.0.0"},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
     }
    },

   "runtimes":{
      "win7-x64": { },
      "win7-x86": { },
      "osx.10.10-x64": { },
      "osx.10.11-x64": { },
      "ubuntu.14.04-x64":{ },
      "centos.7-x64":{}
   }

}

 

首先我们要dotnet restore,这里我还原的时候有些久,大家耐心等待一下,因为我们设置4个平台。

dotnet publish -r centos.7-x64

 这个生成部署文件的操作是可以跨平台的,在Windows上通过 dotnet publish -r centos.7-x64 命令生成Linux的部署文件,然后将整个部署文件夹上传到Linux服务器。

dotnet test

测试命令用来运行测试项目,使用配置的测试运行程序中定义的测试套件。你会了解更多有关此命令在本教程的后面的章节里了解更详细的内容。 

 

下次我们将深入了解一下到 project.json 文件,并开始尝试在如何构建更复杂的应用程序与新的.Net Core。

posted @ 2016-07-04 07:16  张善友  阅读(22864)  评论(9编辑  收藏  举报