持续更新,也可以通过我的网站访问,欢迎探讨交流
快速入门
安装
查看dotnet sdk 版本
$ dotnet --version`2.1.4
创建项目目录
$ mkdir study$ cd study
使用 dotnet new
命令创建项目
$ dotnet new console -n Demo$ cd Demo
在 VS Code中打开Demo文件夹
一个最小的应用
打开 Program.cs
using System;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;namespace Demo{ class Program { static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .Build(); host.Run(); } } class Startup { public void Configure(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Hello, World!"); }); } }}
安装相关的Nuget包
$ dotnet add package Microsoft.AspNetCore.Hosting --version 2.0.1$ dotnet add package Microsoft.AspNetCore.Server.Kestrel --version 2.0.1
下载依赖项
$ dotnet restore
运行
$ dotnet run
输出结果:
Hosting environment: ProductionContent root path: C:\netcore\study\Demo\bin\Debug\netcoreapp2.0\Now listening on: http://localhost:5000Application started. Press Ctrl+C to shut down.
项目模板
根据指定的模板,创建新的项目、配置文件或解决方案。
$ dotnet new -h使用情况: new [选项]选项: -h, --help 显示有关此命令的帮助。 -l, --list 列出包含指定名称的模板。如果未指定名称,请列出所有模板。 -n, --name 正在创建输出的名称。如果未指定任何名称,将使用当前目录的名 称。 -o, --output 要放置生成的输出的位置。 -i, --install 安装源或模板包。 -u, --uninstall 卸载一个源或模板包。 --type 基于可用的类型筛选模板。预定义的值为 "project"、"item" 或 "other"。 --force 强制生成内容,即使该内容会更改现有文件。 -lang, --language 指定要创建的模板的语言。模板 短名称 语言 标记-------------------------------------------------------------------------------- ------------------------Console Application console [C#], F#, VB Common/ConsoleClass library classlib [C#], F#, VB Common/LibraryUnit Test Project mstest [C#], F#, VB Test/MSTestxUnit Test Project xunit [C#], F#, VB Test/xUnitASP.NET Core Empty web [C#], F# Web/EmptyASP.NET Core Web App (Model-View-Controller) mvc [C#], F# Web/MVCASP.NET Core Web App razor [C#] Web/MVC/Razor PagesASP.NET Core with Angular angular [C#] Web/MVC/SPAASP.NET Core with React.js react [C#] Web/MVC/SPAASP.NET Core with React.js and Redux reactredux [C#] Web/MVC/SPAASP.NET Core Web API webapi [C#], F# Web/WebAPIglobal.json file globaljson ConfigNuGet Config nugetconfig ConfigWeb Config webconfig ConfigSolution File sln SolutionRazor Page page Web/ASP.NETMVC ViewImports viewimports Web/ASP.NETMVC ViewStart viewstart Web/ASP.NETExamples: dotnet new mvc --auth Individual dotnet new page --namespace dotnet new --help
使用dotnet new
选择 console 模板 创建项目
$ dotnet new console -n Demo$ cd Demo
创建后的项目文档结构是
.├── Demo│ ├── Demo.csproj│ └── Program.cs
路由
启用,配置路由
using System;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;namespace Demo { class Startup { public void ConfigureServices (IServiceCollection services) { //启用路由 services.AddRouting (); } public void Configure (IApplicationBuilder app) { //配置路由 app.UseRouter (routes => { //根路由 (/) routes.MapGet("", context => { return context.Response.WriteAsync("Hello, World!"); }); //在根路由 (/) 上,配置 /hello Get请求的路由 routes.MapGet ("hello", context => { return context.Response.WriteAsync ("Got a Get request at /hello"); }); }); } }}
安装相关的Nuget包
$ dotnet add package Microsoft.AspNetCore.Routing --version 2.0.1
下载依赖项
$ dotnet restore
运行
$ dotnet run
访问 http://localhost:5000/hello ,输出结果:
Got a Get request at /hello
对 /user 路由的 POST 请求进行响应:
routes.MapPost("hello", context => { return context.Response.WriteAsync ("Got a Post request at /hello");})
对 /user 路由的 PUT 请求进行响应:
routes.MapPut("hello", context => { return context.Response.WriteAsync ("Got a Put request at /hello");})
对 /user 路由的 DELETE 请求进行响应:
routes.MapDelete("hello", context => { return context.Response.WriteAsync ("Got a Dlete request at /hello");})
静态文件
启用,配置静态资源
创建 wwwroot文件夹
$ mkdir wwwroot$ cd wwwroot
复制 index.html 到 wwwroot目录
$ mkdir images$ cd images
复制 favicon.png 到 images文件夹下
项目结构图如下:.├── Demo│ ├── wwwroot│ │ ├── images│ │ │ ├── favicon.png│ │ ├── index.html│ ├── Demo.csproj│ └── Program.cs
更改 Program.cs,设置ContentRoot路径为当前项目根目录,启用静态资源
using System;using System.IO;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;namespace Demo { class Program { static void Main (string[] args) { Console.WriteLine (AppContext.BaseDirectory); var host = new WebHostBuilder () .UseKestrel () //设置 ContentRoot, ContentRoot是任何资源的根路径,比如页面和静态资源 .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build (); host.Run (); } } class Startup { public void Configure (IApplicationBuilder app) { //使用静态资源,默认的目录是 /wwwroot app.UseStaticFiles (); } }}
运行
http://localhost:5000/index.html
http://localhost:5000/images/favicon.png
配置其他文件夹
新建文件夹myfiles
$ mkdir myfiles$ cd myfiles
创建一个新的 index.html到myfiles文件夹,配置并使用myfiles文件夹
app.UseStaticFiles (new StaticFileOptions { FileProvider = new PhysicalFileProvider ( Path.Combine (Directory.GetCurrentDirectory (), "myfiles")), RequestPath = "/myfiles"});
运行
http://localhost:5000/myfiles/index.html
页面渲染
Razor模板引擎
Asp.net Core自带的模板引擎是 Razor模板引擎,传统的Razor页面以cshtml结尾, 阅读Razor语法
遗憾的是Razor模板引擎在Asp.net Core中封装在了MVC模块之中,需要做一些扩展才可以单独拿出来使用
创建模板页面
创建 views文件夹
$ mkdir views$ cd views
创建 index.cshtml 页面
<!DOCTYPE html><html><head> <meta charset="utf-8" /></head><body> <ul> @for (int i = 0; i < 5; i++) { <li>第@(i + 1)行</li> } </ul></body></html>
使用模板
using System;using System.IO;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;namespace Demo{ class Program { static void Main(string[] args) { Console.WriteLine(AppContext.BaseDirectory); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } class Startup { public void ConfigureServices(IServiceCollection services) { //启用Mvc services.AddMvc(); //扩展类 services.AddSingleton<RazorViewRenderer>(); } public void Configure(IApplicationBuilder app) { app.UseRouter(routes => { //根路径 / routes.MapGet("", context => { return context.Render("/views/index.cshtml"); } }); } }}
安装相关的Nuget包
$ dotnet add package Microsoft.AspNetCore.Mvc --version 2.0.2
下载依赖项
$ dotnet restore
运行
$ dotnet run
结果
第1行第2行第3行第4行第5行
渲染数据
新增实体类 UserInfo
public class UserInfo{ public string Name { get; set; } public int Age { get; set; }}
新增user.cshtml页面
@using Demo;@model UserInfo<!DOCTYPE html><html><head> <meta charset="utf-8" /></head><body> <ul> <li>姓名:@Model.Name</li> <li>年龄:@Model.Age</li> </ul></body></html>
更改Program.cs
app.UseRouter(routes =>{ //根路径 / routes.MapGet("", context => { return context.Render("/views/index.cshtml"); } routes.MapGet("/user", context => { return context.Render("/views/user.cshtml", new UserInfo() { Name = "张三", Age = 18 }); });});
运行
$ dotnet run
结果
姓名:张三年龄:18
请求数据
QueryString
var queryCollection = context.Request.Query;foreach (var item in queryCollection){ Console.WriteLine(item.Key + ":" + item.Value);}
Form
if (context.Request.ContentType.ToLower().Contains("application/x-www-form-urlencoded"){ var formCollection = context.Request.Form; foreach (var item in formCollection) { Console.WriteLine(item.Key + ":" + item.Value); }}
Files
var fileCollections = context.Request.Form.Files;var rootPath = context.RequestServices.GetService<IHostingEnvironment>().ContentRootPath;foreach (var item in fileCollections){ var path = Path.Combine(rootPath,item.FileNa using (var stream = new FileStream(path, FileMode.Create)) { await item.CopyToAsync(stream); } Console.WriteLine(item.FileName + ":" + item.Length);}
Header
var headerCollection = context.Request.Headers;foreach (var item in headerCollection){ Console.WriteLine(item.Key + ":" + item.Value);}
Body
StreamReader reader = new StreamReader(context.Request.Body);string text = reader.ReadToEnd();
Cookies
var cookieCollection=context.Request.Cookies;foreach (var item in cookieCollection){ Console.WriteLine(item.Key + ":" + item.Value);}
错误和重定向
重定向
context.Response.Redirect("path")
状态代码页
using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Diagnostics;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;using System;using System.IO;using System.Text.Encodings.Web;namespace Demo{ class Program { static void Main(string[] args) { Console.WriteLine(AppContext.BaseDirectory); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } class Startup { public void ConfigureServices(IServiceCollection services) { //启用路由 services.AddRouting(); services.AddMvc(); services.AddSingleton<RazorViewRenderer>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //启用状态码页 app.UseStatusCodePages(); app.UseRouter(routes => { //根路径 / routes.MapGet("", context => { return context.Render("/views/index.cshtml"); }
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。