在Mac下运行ASP.NET Core应用程序
在Mac下运行ASP.NET Core应用程序
通过参照.NET Core相关官方文档,在我的Mac电脑上用Visual Studio Code创建了我的第一个ASP.NET应用。
开发环境搭建
首先要先安装.Net Core和Visual Studio Code,并且要给Visual Studio Code安装
C# extension,另外要到nodejs.org
安装Node.js和npm。
利用Yeoman搭建应用
由于我们在安装Node.js时自带的npm地址是墙外,npm install有可能没有反应或者很卡。所以本文所有的npm安装都使用了淘宝NPM镜像:
npm install cnpm -g --registry=https://registry.npm.taobao.org

使用npm安装必要的yeoman generators和bower。
sudo cnpm install -g yo generator-aspnet bower

Yeoman的logo是一个戴帽子的男人。它其实是一个工作流,这个工作流包含了三种用来提升你构建一个Web应用的生产力和满意度的工具:
脚手架工具(yo), 构建工具(Gulp,Grunt等), 包管理工具(比如npm和Bower)。
使用yo aspnet
来运行ASP.NET Core generator,以生成一个Web Application基础模板。
yo aspnet
yo aspnet
生成的模板都是基于大家熟悉的Visual Studio 2015上的模板,这个模板维护在ASP.NET Templates project。

然后会提示What type of application do you want to create?
这里选择Web Application Basic [without Membership and Authorization]
并回车。
接着会提示Which UI framework would you like to use?

这里选择Bootstrap (3.3.6) as the UI framework
并回车。
用MyFirstApp
作为应用名称并回车。如下图:


此时generator会生成项目的基础框架文件,然后提示你分别执行restore,build,run命令。
Your project is now created, you can use the following commands to get going
cd "MyFirstApp"
dotnet restore
dotnet build (optional, build will also happen with it‘s run)
dotnet run




至此,打开本地的浏览器在地址栏输入:http://localhost:5000
,即可访问你创建的第一个程序。
使用Visual Studio Code开发应用
用Visual Studio Code打开刚刚创建的项目,通过快捷键⌘⇧P
输入dot
,选择dotnet: Restore Packages
来restore必要的build和debug项目依赖。可以在VS Code中直接运行包括dotnet restore
在内的命令和所有在project.json文件中引用到的工具以及在.vscode/tasks.json
中自定义的任务。

你还可以通过快捷键⌃`调出集成在VS Code里面的控制台。

对于未被用到的using
语句会被标记一道绿色波浪线,鼠标移到上面还有显示一个黄色小灯泡,此时你可以使用⌘ .
移除它们;类和方法也会显示它们在该项目中被引用的次数;还可以通过⌘KC
来添加代码块注释,通过⌘KU
来取消注释。

点击VS Code左侧调试窗格中的绿色三角形的调试按钮,可能会在顶部出现一个错误提示信息:

根据错误提示可知,我们需要配置launch.json
文件里面的program
为实际的可执行文件。

配置成功后,我们可以给程序设置断点、添加监视等。

最终程序会调出本地默认的浏览器程序并导航到http://localhost:5000
,效果如下:

基于Kestrel本地运行应用
本示例采用Kestrel作为Web服务器,可以在project.json里看到它被作为一个依赖项。

KestrelHttpServer服务器是微软推出的唯一一款基于跨平台网络库libuv的跨平台Web服务器。
通过代码可以发现通过调用IWebHostBuilder的UseKestrel扩展方法即可完成对KestrelHttpServer的注册。
namespace Microsoft.AspNetCore.Hosting
{
public static class WebHostBuilderKestrelExtensions
{
public static IWebHostBuilder UseKestrel(this IWebHostBuilder hostBuilder)
{
return hostBuilder.ConfigureServices(services =>
{
services.AddTransient<IConfigureOptions<KestrelServerOptions>, KestrelServerOptionsSetup>();
services.AddSingleton<IServer, KestrelServer>();
});
}
public static IWebHostBuilder UseKestrel(this IWebHostBuilder hostBuilder,
Action<KestrelServerOptions> options)
{
return hostBuilder.UseKestrel().ConfigureServices(services =>
{
services.Configure(options);
});
}
}
}
参考资源
- Building Projects with Yeoman
- generator-aspnet
- Your First ASP.NET Core Application on a Mac Using Visual Studio Code