Fork me on GitHub

尝鲜.net core2.1 ——编写一个global tool

本文内容参考微软工程师Nate McMaster的博文.NET Core 2.1 Global Tools

用过npm开发都知道,npm包都可以以全局的方式安装,例如安装一个http-server服务,可以使用npm i http-server -g来将http-server包安装到全局环境。安装完之后,就可以通过cmd或者powershell运行全局工具http-server命令,来使用静态托管服务。dotnet tool 就是一个类似npm全局工具的新特性,在.net core2.1正式加入。它的详细使用方法可在微软官方文档查看,本文主要介绍如何编写一个global tool并发布至nuget。

安装.net core 2.1

安装最新版.net core SDK 可前往DotNet官方站点的下载页面,下载完成后双击安装即可。安装完成后打开cmd运行dotnet --version 返回版本大于或等于2.1.300表示安装成功。

安装global tool 项目模板

打开cmd 键入dotnet new --install McMaster.DotNet.GlobalTool.Templates安装完成后运行dotnet new

模板                                                短名称                语言                标记
----------------------------------------------------------------------------------------------------------------------------
Console Application                               console            [C#], F#, VB      Common/Console
Class library                                     classlib           [C#], F#, VB      Common/Library
.NET Core Global Console Tool                     global-tool        [C#]              Console/Empty
Unit Test Project                                 mstest             [C#], F#, VB      Test/MSTest
xUnit Test Project                                xunit              [C#], F#, VB      Test/xUnit
Razor Page                                        page               [C#]              Web/ASP.NET
MVC ViewImports                                   viewimports        [C#]              Web/ASP.NET
MVC ViewStart                                     viewstart          [C#]              Web/ASP.NET
ASP.NET Core Empty                                web                [C#], F#          Web/Empty
ASP.NET Core Web App (Model-View-Controller)      mvc                [C#], F#          Web/MVC
ASP.NET Core Web App                              razor              [C#]              Web/MVC/Razor Pages
ASP.NET Core with Angular                         angular            [C#]              Web/MVC/SPA
ASP.NET Core with React.js                        react              [C#]              Web/MVC/SPA
ASP.NET Core with React.js and Redux              reactredux         [C#]              Web/MVC/SPA
Razor Class Library                               razorclasslib      [C#]              Web/Razor/Library/Razor Class Library
ASP.NET Core Web API                              webapi             [C#], F#          Web/WebAPI
global.json file                                  globaljson                           Config
NuGet Config                                      nugetconfig                          Config
Web Config                                        webconfig                            Config
Solution File                                     sln                                  Solution

多出一个global-tool模板

.NET Core Global Console Tool                     global-tool        [C#]              Console/Empty

编写一个网页下载工具

接下来通过编写一个网页下载的小工具来演示global tool的创建过程,此小工具的功能是根据网址,下载相应的页面html并保存为文件。

首先新建一个WebDownloader文件夹。在文件夹中运行dotnet new global-tool生成项目如下

obj
Program.cs
WebDownloader.csproj

打开WebDownloader.csproj修改为

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <ToolCommandName>web-downloader</ToolCommandName>
    <PackAsTool>True</PackAsTool>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="2.2.3" />
  </ItemGroup>

</Project>

打开Program.cs修改为

using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Net.Http;
using McMaster.Extensions.CommandLineUtils;

namespace WebDownloader
{
    [Command(Description = "网页下载小工具")]
    class Program
    {
        public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);

        [Argument(0, Description = "网址")]
        [Required]
        public string Url { get; }

        [Option(Description = "保存路径")]
        public string Path { get; } = "./";

        [Option(Description = "文件名")]
        public string Name { get; } = "content.txt";

        private int OnExecute()
        {
            var client = new HttpClient();
            var content = client.GetStringAsync(Url).Result;
            var path = System.IO.Path.Combine(Path, Name);
            File.WriteAllText(path, content);
            return 0;
        }
    }
}

修改完成后全部保存文件,运行dotnet pack -o ./会在项目根目录生成一个WebDownloader.1.0.0.nupkg包。此包就是最终的nuget包,可上传至nuget.org共享。

为了测试,我们直接将此包安装至本地计算机。运行dotnet tool install WebDownloader -g --add-source ./完成安装。运行 web-downloader -h可以看到项目帮助文档

网页下载小工具

Usage: WebDownloader [arguments] [options]

Arguments:
  Url               网址

Options:
  -p|--path <PATH>  保存路径
  -n|--name <NAME>  文件名
  -?|-h|--help      Show help information

运行 web-downloader http://www.sina.com后我们发现项目根目录生成了一个content.txt文件内容为新浪的首页html

<!DOCTYPE html>
<!-- [ published at 2018-05-31 23:35:00 ] -->
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>新浪首页</title>
	<meta name="keywords" content="新浪,新浪网,SINA,sina,sina.com.cn,新浪首页,门户,资讯" />
	<meta name="description" content="新浪网为全球用户24小时提供全面及时的中文资讯,内容覆盖国内外突发新闻事件、体坛赛事、娱乐时尚、产业资讯、实用信息等,设有新闻、体育、娱乐、财经、科技、房产、汽车等30多个内容频道,同时开设博客、视频、论坛等自由互动交流空间。" />
    <link rel="mask-icon" sizes="any" href="//www.sina.com.cn/favicon.svg" color="red">
	<meta name="stencil" content="PGLS000022" />
	<meta name="publishid" content="30,131,1" />
	<meta name="verify-v1" content="6HtwmypggdgP1NLw7NOuQBI2TW8+CfkYCoyeB8IDbn8=" />
	<meta name="360-site-verification" content="63349a2167ca11f4b9bd9a8d48354541" />
	<meta name="application-name" content="新浪首页"/>
	<meta name ="msapplication-TileImage" content="//i1.sinaimg.cn/dy/deco/2013/0312/logo.png"/>
	<meta name="msapplication-TileColor" content="#ffbf27"/>
	<meta name="sogou_site_verification" content="Otg5irx9wL"/>
<link rel="apple-touch-icon" href="//i3.sinaimg.cn/home/2013/0331/U586P30DT20130331093840.png" />
...
...

如果不再使用此工具通过dotnet tool uninstall WebDownloader -g卸载即可。

posted @ 2018-05-31 23:44  huanent  阅读(1510)  评论(5编辑  收藏  举报