65.9K
CodeProject 正在变化。 阅读更多。
Home

为初学者构建 DotnetcoreAPIAngular6UI

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2019 年 2 月 6 日

CPOL

6分钟阅读

viewsIcon

4921

如何为初学者构建 DotnetcoreAPIAngular6UI

引言

本文旨在为初学者提供开发 .NET Core Web API 和 Angular 6 UI 的指南。这包括 Web API 的 JWT、Swagger、Log4net、中间件配置。Angular UI 包含组件、路由、服务。本文还为有 C# 和 JQuery 背景的开发者提供了一些技巧,帮助他们熟悉 Angular4/5/6 并动手实践。

项目开发

在 VS2017 中创建新项目,选择 ASP.NET Core Web 应用程序 >> API,命名为“CustService”。

安装以下程序包

  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.SqlServer.Design

创建 ModelsService 文件夹。

从程序包管理器控制台中执行以下命令以生成 DBContextModels

Scaffold-DbContext "Server=DataSource;Database=CustomerDB;Trusted_Connection=True;" 
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

这会在 Models 文件夹中创建 CustomerDBContextCustomerUserLogin 类文件。

注释掉上下文文件中的方法 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

创建 ICustomerServiceIAdminService,添加 CRUD 操作所需的函数。

创建 CustomerServiceAdminService,它们继承自 ICustomerServiceIAdminservice 并实现接口的所有方法。在此 Service 中,在构造函数中注入 CustomerDBContext

添加 CustomerControllerAdminController 并为终结点创建操作。由于没有太多业务逻辑,每个服务只有一个 Http* 操作。

配置

appsettings.json 文件中添加 ConnectionStrings(DefaultConnection)

在 Startup.cs 文件中

ConfigureServices 函数中,添加以下行

//DI for Services
services.AddScoped<ICustomerService, CustomerService>();
//DI for DBContext
services.AddScoped<CustomerDBContext>();
//Getting connection String from appsettings.json and add to context.
services.AddDbContext<CustomerDBContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Swagger 配置

安装程序包 Swashbuckle.AspNetCoreSwashbuckle.AspNetCore.SwaggerUI 以配置 Swagger 和测试 API。

添加到 ConfigureServices 方法中

      services.AddSwaggerGen(c =>
           {
               c.SwaggerDoc("v1", new Info { Title = "Customer API", Version = "v1" });
           });

添加到 Configure 方法中

           // Enable middleware to serve generated Swagger as a JSON endpoint.
           app.UseSwagger();

           // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
           // specifying the Swagger JSON endpoint.
           app.UseSwaggerUI(c =>
           {
               c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
           });

日志配置

安装程序包 Microsoft.Extensions.Logging.Log4Net.AspNetCore

添加 log4net.config 文件,其中包含日志记录的配置详细信息。

添加到 Configure 方法中

//bind from log4net.config xml file
loggerFactory.AddLog4Net();

<ItemGroup>
   <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
   <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.3" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.3" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.3" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
   <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="2.2.10" />
   <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.4" />
   <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
   <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="4.0.1" />
 </ItemGroup>

实现 JWT 安全 API

CustomerController 的操作使用 [Authorize] 属性通过 JWT 进行保护。Admincontroller 只有一个 Action authenticate User,它允许匿名用户登录。[AllowAnonymous] 属性可用于匿名访问。

JWT 应用设置

AppSettings 类包含 appsettings.json 中定义的属性。

Secret 可以是任何 GUIDstring

"AppSettings": {
       "Secret": "1eff8d6a-360f-48d2-a115-91f1cc2ece5d"
   }

Startup.csConfigureServices 中配置 appsettings

// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);

配置节的映射在 Startup.cs 文件的 ConfigureServices 方法中完成。区域 JWTConfig

运行应用程序并导航到 URL https://:5327/swagger/index.html

用户身份验证

AdminService 包含 Authenticate 方法,该方法接受 UsernamePassword 作为参数,以验证用户 against Table UserLogin

成功验证后,它使用 JwtSecurityTokenHandler 类生成 JWT(JSON Web Token),该令牌使用存储在 appsettings.json 中的密钥进行数字签名。JWT 令牌会返回给客户端应用程序,该应用程序必须将其包含在 HTTP Authorization 标头中才能访问 [Authorize] API。

Startup.csConfigureServices 方法中为 Swagger 配置 JWT

// Swagger 2.+ support
               var security = new Dictionary<string, IEnumerable<string>>
               {
                   {"Bearer", new string[] { }},
               };
 
               c.AddSecurityDefinition("Bearer", new ApiKeyScheme
               {
                   Description = "JWT Authorization header using the Bearer scheme. 
                            Example: \"Authorization: Bearer {token}\"",
                   Name = "Authorization",
                   In = "header",
                   Type = "apiKey"
               });
               c.AddSecurityRequirement(security);

现在让我们在 Swagger 中测试我们的 API

运行应用程序并打开 URL https://:5327/swagger/index.html

在数据库表 UserLogin 中创建样本记录,其中 username=”testing”password=”testing”

点击 /api/Admin/authenticate,“Try It Out”。

userParam 中输入有效的用户名和密码,然后点击 Execute。响应状态码为“200”,响应体中包含“token”。

复制 Token,用于测试 [Authorized] API。

点击“Authorize”按钮,输入“Bearer”,然后粘贴 Token。它看起来像这样。点击 Authorize 按钮。从 Swagger 进行后续 API 调用时,此 Bearer 令牌将添加到 Authorization 标头中。

在 Swagger 中创建 customer,并提供所需信息,不要输入 CustID,因为它是标识列。

尝试测试“GetAllCustomer” API,以便成功创建 customer

样本 Web API 的开发已完成。

现在我们可以开始在 Angular6 中开发 UI 了

安装 Angular CLI 并验证版本“ng --v

Angular CLI: 6.1.4

Node: 8.11.4

...以及其他已安装的程序包。

创建 Customer UI 命令:“ng new CustomerUI

安装所有程序包可能需要一些时间。

运行以下命令为路由 Module:用于从 List 导航到 Create Customer

ng generate module app-routing --flat --module=app
//Display all Customers
ng g component CustomerList
//Display Customer Details and to add New Customer.
ng g component CustomerDetail
//Login page 
Ng g component login
//generate customer class

此应用程序包含 2 个模型:CustomerUserLogin。创建 2 个类和 2 个服务以与 API 通信。

//generate classes
ng g class customer
Ng g class userlogin
Ng g service customerservice
Ng g service userlogin

创建所需的组件、Class 和服务 Studio 后,代码如下所示

在此,我想给一些来自 Dotnet、Angularjs 背景的新 Angular 4/6 开发者的建议。这可能不那么准确或对初学者有帮助。

功能 Angular 4/6 Dotnet
查看 .html aspx
代码文件 .ts .aspx..cs
添加命名空间 import { FormBuilder, FormGroup, Validators } from '@angular/forms'; using Syste.*
编码语言 typescript C#
新页面 ng generate component.
添加 name*.component.html, component.ts, component.css
添加页面:.aspx 和 aspx.cs 文件
主控页面 app.component.html 充当母版页
母版页 cs 文件 app.component.ts 母版页的代码隐藏文件
可重用表单 模板 用户控件
启动 main.ts >> app.module.ts startup.cs, program.cs
添加模型 ng g class Modelname 添加 cs 文件
添加 Service ng g service servicename 添加 cs 文件
通用资源静态文件存储 资产 wwwroot 或 styles 或 scripts 文件夹。
导航/菜单 路由/导航。
ng generate module app-routing --flat --module=app
菜单/html
导航容器 routes: Routes 并使用容器 <router-outlet></router-outlet> 在母版页/登陆页中 不可用
页面导航 TS 文件:this.router.navigate([this.returnUrl])
html:<a routerLink="/Nav1"> Navigation1 </a>
cs: Response.Redirect, Server.Trasfer
html: <a href='' />
页面生命周期事件 ngOnchanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentCheck, ngAfterViewInit, ngAfterViewcheck, ngDestroy 初始化、加载、验证、事件处理、预渲染、渲染
编码    
当前实例 this (必须使用) this (可选)
调试 debugger; 和 this.showSpinner=false; 常用。与 jquery 相同。 断点
声明 custId :number int CustId
常用数据类型 number, string, Date, boolean int, double, float, string, DateTime, boolean。
构造函数 constructor(protected http: HttpClient) 与类名相同
函数声明 方法名(参数):返回类型
例如:authenticateUser(userLogin:UserLogin):Observable<UserLogin> {}
onSelect(selCust:Customer) {
}
返回类型 方法名(参数)
示例
UserLogin Authenticate(string Username, string Password)
{}
条件 if(condition)
在 html 中:*ngIf
if(condition)
loop 在 ts 文件中:for(let a in array){}
html 文件指令:*ngFor="let curCust of custList"
foreach(var a in list){}
从代码绑定到 html {{curCust.custId}} 服务器控件:controlID.Text
双向绑定 [(ngModel)]="variable" 不可用
在代码文件中访问 DOM html get f() { return this.FormGroupname.controls; }
this.variable=this.f.controlname.value;
runat=server,可以在代码隐藏中访问。
提交表单 form Submit (ngSubmit)="onSubmit()" 表单回发
事件绑定 <button (click)="onClickMe()">Click me!</button>
<input (keyup)="onKey($event)">
object.event + = new delegate(method)

HTML DOM 函数是有效的,例如 document.getElementById,需要导入 FormsModule

打开 app.component.html,删除内容并添加导航内容。

App.module.cs

导入必需的模块。这里是 FormsModule (表单控件和 F),HttpModule(http Requests)HttpClient (API 调用和服务实现)。

userLogincustomer 是两个具有必需属性的类。

服务

这些类负责使用 http 协议发出 API 调用。它导入 HttpClientHttpHeadersHttpParamsRequestContentTypeHttpResponse 模块,这些模块提供了必需的类。此编码与 XMLHttpRequest.,Rxjs 相同。

Components

登录

Formgroup、控件验证和错误显示与 HTML 相同。

OnForm Submit,从表单控件获取用户名、密码并调用 authenticateUser API,如果凭据有效,则返回带有令牌的 currentUser,该令牌存储在 localStorage 中(HTML 5 功能可在组件之间访问。以键值对形式保存)。

CustomerList

它包含一个 HTML 表格来显示 Customer List*ngFor Structure 指令将循环遍历 customerlist 以创建 <tr>。单击 (click) 可选择 tr / currCustomer

ngOnInt 事件在页面初始化时触发,在此事件中调用 getAllcustomer API 来获取 Customers

CustomerDetail 组件

这是一个简单的 FormsControl 页面,用于创建 Customer

常见错误

从 'https://:5327/api/Customer//GetAllCustomer' 访问 XMLHttpRequest 的请求因 CORS 策略而被阻止:预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。

原因:CORS 未启用。
解决方案:必须在 startup.cs 文件中启用 CORS。也可以通过其他方式实现。

401 错误:未授权

原因:Authorize Bearer Token 是问题所在。语法不正确,Token 无效或 API 中的 Token 验证不正确。
解决方案:调试并查找 api 地址和 Token 语法。对于 .NET Core 2.0 版本,请在 startup.cs/Configure 函数中添加 app.UseAuthentication()

© . All rights reserved.