.Net Core入门
这篇想写一下使用.Net Core的基本过程,网上还已经有大把的博客了,我在这里总结一下。
这篇文章应该作为了解.Net Core基础概念后,第一次动手实践的学习。跟据.Net Core的思想和其他平台developer的习惯,选择vscode是最好了。开始动手时要装好Visual Studio Code 和 .NET Core SDK for Windows.
下面是dotnet的常用命令:
dotnet-new
dotnet-restore
dotnet-run
dotnet-build
dotnet-test
dotnet-pack
dotnet-publish
创建一个项目( dotnet new [ -t Console|Web|Lib|xunittest ]
)
![](https://img.haomeiwen.com/i1996846/88d6ebc52b763d64.png)
直接执行“dotnet new”创建的控制台应用只包含如下两个文件,其中包含程序入口方法的所有C#程序定义在Program.cs 中,另一个则是项目描述文件project.json。
说明
dotnet new
命令可通过-t 指定创建的项目类型,一共可创建四种项目类型。
还原包(dotnet restore
)
![](http://upload-images.jianshu.io/upload_images/1996846-de6575cc2ad670e6.png)
执行后,目录中文件多了“project.lock.json”,打开后一打串的json。他表示引用了安装本地计算机中的.Net Core Libriries, 还不知道这个详细的表示是什么。
![](http://upload-images.jianshu.io/upload_images/1996846-fce946a1393755a7.png)
编译运行(dotnet build 及 dotnet run
)
![](http://upload-images.jianshu.io/upload_images/1996846-e2cfcb6b67bd910f.png)
类库创建与打包(dotnet new -lib && dotnet pack
)
创建类库
![](http://upload-images.jianshu.io/upload_images/1996846-5b1db00ac4a41e99.png)
编写代码
![](http://upload-images.jianshu.io/upload_images/1996846-6dcaf4b542eb935f.png)
打包
dotnet restore
dotnet pack
![](http://upload-images.jianshu.io/upload_images/1996846-2d4e7c1c67a3a40e.png)
![](http://upload-images.jianshu.io/upload_images/1996846-a26a9a8fded75493.png)
这是生成的bin目录下的文件就是我们要在主程序中引用的程序集了。
添加离线引用包
在Console项目中的project.json文件中添加一行。
![](http://upload-images.jianshu.io/upload_images/1996846-b69deda91eef7ac2.png)
还原的命令为 dotnet restore -f "D:\Demo\ASP.NET Core\HelloLib\bin\Debug"
![](http://upload-images.jianshu.io/upload_images/1996846-f06dc471d35d94a2.png)
没有问题,下面我们使用刚编写的方法。编写主程序:
![](http://upload-images.jianshu.io/upload_images/1996846-27349a34e68562ee.png)
运行
![](http://upload-images.jianshu.io/upload_images/1996846-f1806097c4ff14b1.png)
测试(dotnet test
)
这是需要新建文件夹,新建测试项目: dotnet new -t xunittest
![](http://upload-images.jianshu.io/upload_images/1996846-a6e48a6f4f20b136.png)
接着编写测试方法。我略过了...
还原
dotnet restore
,测试 dotnet test
![](http://upload-images.jianshu.io/upload_images/1996846-0f36a1c22b1d8606.png)
发布(dotnet publish
)
默认发布,执行命令dotnet publish
![](http://upload-images.jianshu.io/upload_images/1996846-6668a24be70d4907.png)
程序生成在目录
** D:\Demo\ASP.NET Core\HelloConsole\bin\Debug\netcoreapp1.0\publish**
![](http://upload-images.jianshu.io/upload_images/1996846-833db5e6004beff3.png)
这是还需要 使用 dotnet 来运行程序。
下面重点来了,夸平台发布:
在project.json文件中删掉"type": "platform", 添加runtimes节点
![](http://upload-images.jianshu.io/upload_images/1996846-e144d1f5cee44b3b.png)
然后重新还原发布 dotnet restore && dotnet publish -r win10-x64
这样就算完了。 但这里报错,可能是我的环境什么有问题吧!如果有人知道怎么回事,还请告诉我一下。
![](http://upload-images.jianshu.io/upload_images/1996846-64298b8082b04469.png)
补充
dotnet -t web 创建的项目实际上是个完整的MVC的Web项目。喜欢MVC的人心里也算得到了些许的安慰。 夸平台.Net Core+MVC 才是微软下一代比较好的方案。