发布dll
# 发布dll
waterlibrary build
piliplugin build
pilipala build
将所有依赖项配置好
# MySQL
导入mysql
把发布出来的文件塞到ftp里
# dotnet public
使用systemd
申请证书
为nginx配置https
# dotnet
大多数开发人员日常使用的主要命令就是还原、生成、运行、测试
# dotnet 命令目录:
dotnet-new
dotnet-restore
dotnet-run
dotnet-build
dotnet-test
dotnet-pack
dotnet-publish
# 创建(dotnet new)
dotnet new 开发应用程序
dotnet new --help 帮助,查看选项
dotnet new --list 查看所有的模板
命令行输入 " dotnet new ", 显示如下:
Usage: new [options]
Options:
-h, --help Displays help for this command.
-l, --list Lists templates containing the specified name. If no name is specified, lists all templates.
-n, --name The name for the output being created. If no name is specified, the name of the current directory is used.
-o, --output Location to place the generated output.
-i, --install Installs a source or a template pack.
-u, --uninstall Uninstalls a source or a template pack.
--type Filters templates based on available types. Predefined values are "project", "item" or "other".
--force Forces content to be generated even if it would change existing files.
-lang, --language Specifies the language of the template to create.
Templates Short Name Language Tags
--------------------------------------------------------------------------------------------------------
Console Application console [C#], F#, VB Common/Console
Class library classlib [C#], F#, VB Common/Library
Unit Test Project mstest [C#], F#, VB Test/MSTest
xUnit Test Project xunit [C#], F#, VB Test/xUnit
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
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
Razor Page page Web/ASP.NET
MVC ViewImports viewimports Web/ASP.NET
MVC ViewStart viewstart Web/ASP.NET
Examples:
dotnet new mvc --auth Individual
dotnet new viewimports --namespace
dotnet new --help
创建一个winform应用程序 dotnet new winforms -o Blue
创建一个webdotnet new web -o Bright
创建一个控制台应用程序dotnet new console -n FirstApplication or dotnet new console -o FirstApplication
The template "Console Application" was created successfully.
Processing post-creation actions...
Running 'dotnet restore' on Green\Green.csproj...
D:\test_dot_net\Green\Green.csproj 的还原在 329.26 ms 内完成。
Restore succeeded.
D:\test_dot_net>cd Green
D:\test_dot_net\Green>dotnet run
Hello World!
我们切换到FirstApplication文件中,可以看到现在已经有三个文件.简单讲解一下:
- FirstApplication.csproj .csproj为项目构建文件(C Sharp Project”)
- Program.cs 为程序的主入口, 有一个静态的Main方法
- obj用于存放编译过程中生成的中间临时文件,一般不用管
# dotnet run
执行 dotnet run输出:Hello World!
# 还原(dotnet restore 及 dotnet pack)
寻找当前目录下的项目文件(project.json),然后利用NuGet库还原整个项目的依赖库,然后遍历每个目录,生成项目文件,继续还原该项目文件中的依赖项。
dotnet restore
是一个隐式的命令,需要还原的时候会自动执行 dotnet restore
命令。下面的命令执行时都会隐式调用还原。
new
run
build
publish
pack
test
当然,也可以给这些命令传递 --no-restore
选项,禁用隐式还原。
我们创建一个 应用程序
创建好以后,编写一些自己的代码然后进行打包。
dotnet restore
dotnet pack
.NET Core 怎样添加离线引用包呢?
打包好以后,我们将applib 添加到 app的 project.json 。
添加好以后切到app 目录,然后进行还原。
还原使用的命令是:dotnet restore -f E:\dotnet\applib\bin\Debug\
dotnet restore -f 包的路径
这样我们就能直接在项目里调用applib 里面的方法。
我们在代码里编写对应的调用,然后执行程序。可以看到正确输出class lib 的结果。
# 运行(dotnet build 及 dotnet run)
dotnet build 编译代码
dotnet run 执行程序
C:\Users\zervan\Desktop\OG\Green>dotnet run Hello World!
dotnet xx.dll 也是执行程序
# 测试(dotnet test)
这里我们要新建一个文件夹及项目了。
新建测试项目: dotnet new -t xunittest
新建好项目我们可以在里面添加测试方法,这里我直接运行测试。
dotnet restore
dotnet test
# 发布(dotnet publish)
重点来了,发布项目使其可以跨平台运行。
dotnet publish 默认发布
发布后定位到publish目录使用 dotnet xx.dll 执行应用。
# 下面来跨平台发布。
在 project.json 加入 runtimes 节点 注释掉 "type": "platform"。
首先我们要dotnet restore
这里我还原的时候有些久,大家耐心等待一下。
dotnet publish -r win10-x64
这里发布后,可以直接定位到发布publish目录,执行 app.exe 即可。
dotnet publish -r ubuntu.14.04-x64
将publish 文件夹上传至linux系统 ,设置app的权限为可执行,然后 ./app 就可以运行了。
dotnet publish -r 指定runtimes节点里系统ID
# ASP.NET Core
ASP.NET Core 是一个新的开源和跨平台的框架,用于构建如 Web 应用、物联网(IoT)应用和移动后端应用等连接到互联网的基于云的现代应用程序。ASP.NET Core应用可运行于 .NET Core 和完整的 .NET Framework 之上。 构建它的目的是为那些部署在云端或者内部运行(on-premises)的应用提供一个优化的开发框架。它由最小开销的模块化的组件构成,因此在构建你的解决方案的同时可以保持灵活性。你可以在 Windows、Mac 和 Linux 上跨平台的开发和运行你的ASP.NET Core应用。
# 创建ASP.NET Core程序
开发环境: dotnet SDK + VS Code
首先我们创建一个项目 ,这里我们创建mvc框架。
dotnet new mvc
C:\Users\zervan\Desktop\C#>dotnet new mvc
已成功创建模板“ASP.NET Core Web App (Model-View-Controller)”。
正在处理创建后操作...
在 C:\Users\zervan\Desktop\C#\C#.csproj 上运行 “dotnet restore”...
正在确定要还原的项目…
已还原 C:\Users\zervan\Desktop\C#\C#.csproj (用时 166 ms)。
已成功还原。
这里还是直接使用dotnet new命令来创建ASP.NET Core项目, 终端中输入"dotnet new web -n FirsrMVC".
自动创建FirsrMVC文件夹并生成对应的csproj和CS文件,具体操作和输出信息如下:
➜ codelover-blog git:(master) ✗ dotnet new web -n FirsrMVC
The template "ASP.NET Core Empty" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.
Processing post-creation actions...
Running 'dotnet restore' on FirsrMVC/FirsrMVC.csproj...
Restoring packages for /Users/liguobao/code/codelover-blog/FirsrMVC/FirsrMVC.csproj...
Generating MSBuild file /Users/liguobao/code/codelover-blog/FirsrMVC/obj/FirsrMVC.csproj.nuget.g.props.
Generating MSBuild file /Users/liguobao/code/codelover-blog/FirsrMVC/obj/FirsrMVC.csproj.nuget.g.targets.
Restore completed in 1.97 sec for /Users/liguobao/code/codelover-blog/FirsrMVC/FirsrMVC.csproj.
Restore succeeded.
➜ codelover-blog git:(master) ✗ cd FirsrMVC
➜ FirsrMVC git:(master) ✗ ls
FirsrMVC.csproj Program.cs Startup.cs obj/ wwwroot/
# Program.cs
打开FirsrMVC文件夹,简单看一下文件和Program.cs的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace C_
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Program.cs依旧是Main主方法,然后调用了一下BuildWebHost方法,BuildWebHost返回一个IWebHost的实例,接着Run.
先不管这里具体做了什么事情,我们从语义上理解一下.
- BuildWebHost构建一个Web的Host实例,然后把WebHost实例运行起来了
- 创建WebHost使用了一个Startup的类
- 关于详细WebHost的详细解析见:ASP.NET Core 运行原理解剖 (opens new window)
# Startup.cs
先直接上一波代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace FirsrMVC
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//直接往HTTP Response中写入"Hello World!",即在页面直接显示此字符
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
- ConfigureServices:运行时被调用,将服务(services)添加到容器(container)中
- Configure:运行时被调用, 配置HTTP request 的pipeline
嗯,看不懂?没关系,待会一个个演示.
我们这里还是直接先跑一下程序,FirsrMVC文件夹路径下执行:dotnet run 输出如下:
➜ FirsrMVC git:(master) ✗ dotnet run
Hosting environment: Production
Content root path: /Users/liguobao/code/codelover-blog/FirsrMVC
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
然后访问http://localhost:5000 (opens new window)。
页面将会输出hello world
# wwwroot中的静态文件
- 在wwwroot文件夹新增first.html,随便写个能看见的HTML标签(我写的是p标签)
- 在 Configure 方法中添加一句 app.UseStaticFiles(); 然后再重新运行一下
- 访问http://localhost:5000/first.html (opens new window)
输出First HTML Page.
本步骤完成.
UseStaticFiles()方法:调用一个读取wwwroot文件夹下面的静态文件输出的中间件注册到程序中,从而完成静态文件的输出.
这里也告诉我们,ASP.NET Core的静态文件(JS+CSS+图片...)之类的都可以放这边来.
甚至于如果简单做前后端分离的话,前端的vue/react项目都可以扔这里去.
# MVC
MVC模式最早由Trygve Reenskaug在1978年提出[1],是施乐帕罗奥多研究中心(Xerox PARC)在20世纪80年代为程序语言Smalltalk发明的一种软件架构。MVC模式的目的是实现一种动态的程式设计,使后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。除此之外,此模式通过对复杂度的简化,使程序结构更加直观。软件系统通过对自身基本部分分离的同时也赋予了各个基本部分应有的功能。
- 控制器(Controller)- 负责转发请求,对请求进行处理。
- 视图(View) - 界面设计人员进行图形界面设计。
- 模型(Model) - 程序员编写程序应有的功能(实现算法等等)、数据库专家进行数据管理和数据库设计(可以实现具体的功能)。
在ASP.NET Core,MVC模型一般就对应着三个文件夹,Models/Views/Controllers.
Models:存放一些业务实体类,如Student,Course等,表现上就是C#的.cs文件
Views:存放CSHTML文件,ASP.NET Core的模板文件,类HTML,也可以写C#代码
Controllers: cs文件,继承Controller类的XXXController,实现业务逻辑代码
下面一起来写一个简单的MVC玩玩.
# Startup
修改 Startup.cs的代码,新增MVC中间件的引用,操作如下:
- Startup.cs中的ConfigureServices方法下新增:services.AddMvc();
- Configure方法下去掉之前的UseMvc,改成
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
全部代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FirsrMVC
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
# Controllers
新增Controllers文件夹,在此文件下新建HomeController.cs文件,然后填入一下代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace FirsrMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
return Json(new { name = "我的名字", success = true });
}
}
}
到这里,我们先运行一下代码.
如无意外的话,
访问http://localhost:5000/ (opens new window) 空白一片,
访问http://localhost:5000/Home/About (opens new window) 会输出
{
"name": "我的名字",
"success": true
}
# http://localhost:5000/ (opens new window)
其实这里访问的是http://localhost:5000/Home/Index (opens new window),对应方法是HomeController/Index
我们看一下Log输出会发现这样的一句错误"fail: The view 'Index' was not found. Searched locations: /Views/Home/Index.cshtml, /Views/Shared/Index.cshtml"
原因是HomeController中的Index返回的是View,
程序默认就会去/Views/目录下寻找/Home/Index.cshtml文件来渲染然后返回给浏览器,但是这里我们并没有这个文件,所以直接GG.
# http://localhost:5000/Home/About (opens new window)
对应方法是HomeController/About,返回为Json数据,不需要View.
所以直接就往浏览器输出了{ name = "我的名字", success = true }的Json格式数据
# Views
上一步我们的的Controller已经建好了,但是缺View文件,我们这里来创建一下View文件
新建Views/Home文件夹,然后再在此文件夹下新增Index.cshtml文件
然后在Index.cshtml中输入:
<p>First View Page</p>>
刷新一下http://localhost:5000/ (opens new window)页面.
输出First View Page
View文件也建立好了.
# Models
最后简单讲一下Model.
同理,新建Models文件夹,在此文件夹下新增Student.cs文件.
namespace FirsrMVC
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
}
我们想做的要做的是把Student信息通过Controller返回给View,然后用View渲染出来.
修改一下HomeController/Index方法:
public IActionResult Index()
{
Student student = new Student() { Name = "小明", Age = 16 };
return View(student);
}
修改一下Views/Home/Index.cshtml
@model FirsrMVC.Student
@if(Model !=null)
{
<p>@Model.Name<span>今年</span>@Model.Age<span>岁</span></p>
}else
{
<p>这里什么都没有.</p>
}
重新运行一下程序,访问http://localhost:5000/ (opens new window)
输出‘小明今年16岁’
MVC结束.
# 结尾
# dotnet core(读取配置文件)
一般dotnet core配置文件都位于项目目录下,名为appsettings.json
# 直接读文件
{
"MySQLConnectionString": "server=mysql地址;port=端口号;database=数据库名字;uid=账号;pwd=密码;charset='utf-8';Allow User Variables=True;Connection Timeout=30;SslMode=None;",
"RedisConnectionString": "redis数据库地址:端口,name=名字,keepAlive=1800,syncTimeout=10000,connectTimeout=360000,password=访问密码,ssl=False,abortConnect=False,responseTimeout=360000,defaultDatabase=1",
"EmailAccount": "QQ邮箱账号",
"EmailPassword": "QQ邮箱密码",
"EmailSMTPDomain": "smtp.qq.com",
"EmailSMTPPort": 587,
"SenderAddress": "QQ邮箱账号",
"ReceiverAddress": "QQ邮箱账号",
"ReceiverName": "liguobao-test",
"EncryptionConfigCIV": "加密向量,16个16进制数字",
"EncryptionConfigCKEY": "加密秘钥,16个16进制数字",
"ESURL":"http://127.0.0.1:9201/",
"ESUserName":"",
"ESPassword":"",
"QQAPPID":"",
"QQAPPKey":"",
"QQAuthReturnURL":""
}
那么我们直接去读json然后序列化成对象是不是就可以了.
没毛病,确实是可以这样玩的. 代码大概是这样的...
public class AppSettings
{
public string MySQLConnectionString {get;set;}
public string RedisConnectionString {get;set;}
// ....
}
public AppSettings JsonHelper(string jsonFilePath)
{
_movieJsonFilePath = jsonFilePath;
if (!File.Exists(jsonFilePath))
{
var pvFile = File.Create(jsonFilePath);
pvFile.Flush();
pvFile.Dispose();
return;
}
using (var stream = new FileStream(jsonFilePath, FileMode.OpenOrCreate))
{
try
{
StreamReader sr = new StreamReader(stream);
JsonSerializer serializer = new JsonSerializer
{
NullValueHandling = NullValueHandling.Ignore,
Converters = { new JavaScriptDateTimeConverter() }
};
//构建Json.net的读取流
using (var reader = new JsonTextReader(sr))
{
return serializer.Deserialize<AppSettings>(reader);
}
}
catch (Exception ex)
{
return null;
}
}
}
直接读文件然后反序列化实在有点麻烦,这时可以直接使用ConfigurationBuilder 读取
# 使用ConfigurationBuilder 读取
直接上代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var mySQLConnectionString = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build()["MySQLConnectionString"];
// ConnectionStrings节点下的MySQLConnectionString
// var mySQLConnectionString = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json").Build()["ConnectionStrings:MySQLConnectionString"];
}
嗯,就是这么简单粗暴,什么都不管...
比起这个,我们还有更优雅点的方法
比如上DI(自动注入)
# DI读取配置文件
//Startup.cs
public IConfiguration Configuration { get; }
public Startup(IHostingEnvironment env)
{
//够赞
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//将Configuration注入到APPConfiguration实例中
services.AddOptions().Configure<AppSettings>(Configuration);
}
然后我们在Controller中使用构造函数注入的方式获取APPConfiguration实例
private AppSettings configuration;
public AccountController(IOptions<AppSettings> configurationOption)
{
this.configuration = configurationOption.Value;
}