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

ASP.NET Core 1.0 RC2 和 Angular2 使用 WEB API

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (8投票s)

2016 年 7 月 10 日

CPOL

9分钟阅读

viewsIcon

45536

downloadIcon

841

在本文中,我们将详细了解如何在 ASP.NET Core 1.0 RC2 中使用 WEB API 来集成 Angular2。

引言

在本文中,我们将详细介绍如何在 ASP.NET Core 1.0 RC2 中使用 WEB API 来集成 Angular2。

在我们上一篇文章  https://codeproject.org.cn/Articles/1084085/ASP-NET-Core-MVC-Using-WEB-API-And-AngularJS  中,我们已经了解了 ASP.NET Core 1.0 和 AnfularJS 的一些基础知识,现在我们将详细介绍在 ASP.NET Core RC2 中使用 WEB API 和 Angular2。

在本文中,我们将详细介绍如何

  • 创建我们的 ASP.NET Core 1.0 RC2 Web 应用程序。
  • 创建 MVC 模型以添加学生详细信息。
  • 创建 MVC 控制器以返回 WEB API 方法
  • 如何添加 TypeScript JSON 配置文件
  • 如何使用 NPM 配置文件添加 Grunt 包
  • 如何配置 Grunt 文件。
  • 添加依赖项以安装 Angular2 和所有其他文件
  • 如何创建我们的 Angular2 应用,使用 TypeScript 文件引导。
  • 创建 HTML 文件
  • 如何使用 Visual Studio 任务运行器资源管理器运行 Grunt 文件
  • 现在是时候运行并查看我们的示例了。
  • 如何在 HTML 页面中显示 Angular2 组件结果。

参考网站: https://angular.io/docs/ts/latest/tutorial/

https://angular.io/docs/ts/latest/guide/server-communication.html

必备组件

Visual Studio 2015: 您可以从 这里 下载。

ASP.NET Core 1.0 RC2: 下载链接 https://www.microsoft.com/net

https://www.microsoft.com/net/core#windows

使用代码

安装完 Visual Studio 2015 和 ASP.NET Core 1.0 RC2 后。单击开始,然后单击程序,然后选择 Visual Studio 2015 - 单击 Visual Studio 2015。单击新建,然后单击项目,选择 Web,然后选择 ASP.NET Core Web 应用程序。输入您的项目名称,然后单击确定。

接下来选择 Web 应用程序。如果您不托管在云中,则可以取消选中右下角的“托管在云中”。单击确定

现在我们已经创建了我们的 ASP.NET Core 1.0 Web 应用程序。

第 2 步:创建 MVC 模型以返回学生列表

我们可以通过在 Model 文件夹中添加一个新类文件来创建模型。

右键单击 Models 文件夹,然后单击新建项。选择 Class,然后将类名输入为“StudentMasters.cs”

现在在此类中,我们首先创建属性变量,将学生详细信息添加到列表中并返回列表。我们将在控制器中使用此列表。

public class StudentMasters
    {
        public int StdID { get; set; }
        public string StdName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }

        public StudentMasters(int ID, string Name, string email, string phone, string Addr)
        {
            StdID = ID;
       StdName = Name;
       Email = email;
        Phone = phone;
            Address = Addr;
    }

        public static List<StudentMasters> studetndDetails()
        {
            List<StudentMasters> listStudents = new List<StudentMasters>();
            listStudents.Add(new StudentMasters(1, "Shanu",  "shanu@shanumail.com",  "000000",  "korea"));
            listStudents.Add(new StudentMasters(2, "Afraz", "Afraz@gmail.com", "0000123", "korea"));
            listStudents.Add(new StudentMasters(3, "Afreen", "Afreen@gmail.com", "000643", "Seoul,Korea"));
            listStudents.Add(new StudentMasters(4, "Asha", "Asha@gmail.com", "00003455", "Madurai,India"));
            listStudents.Add(new StudentMasters(5, "Kather", "Kather@gmail.com", "000067567656", "Madurai,India"));

            return listStudents;
        }
    }

第 3 步:创建 MVC 控制器以返回 WEB API 方法

我们可以通过在 Controller 文件夹中添加一个新建的 Empty API Controller 来创建控制器。

右键单击 Controller 文件夹,然后选择 Add Controller。选择 Empty API Controller,并将名称命名为“StudentMastersController”

在控制器中,我们将 List 结果返回为 IEnumerable。在我们的 Angular2 组件中,我们将使用此 web API 方法来返回数据并将其绑定到我们的 HTML 页面。

[Produces("application/json")]
    [Route("api/StudentMasters")]
    public class StudentMastersController : Controller
    {

        [HttpGet]
        public IEnumerable<StudentMasters> Get()
        {
            return StudentMasters.studetndDetails().ToList();
        }
    }

为了测试它,我们可以运行我们的项目并复制 get 方法的 api 路径,在这里我们可以看到我们 get 的 API 路径是 api/StudentMasters/

运行程序并粘贴上述 API 路径以测试我们的输出。

第 4 步:如何添加 TypeScript JSON 配置文件

TypeScript JSON 文件将指定项目所需的根文件和编译器选项。要了解有关 TypeScript JSON 配置的更多信息,请访问这些网站

https://typescript.net.cn/docs/handbook/tsconfig-json.html ,

要创建 TypeScript JSON 文件,请右键单击您的项目,然后单击添加新项。

选择 TypeScript JSCON Configuration File,然后单击确定。文件将如下所示。

现在复制以下代码并替换您的配置文件。

"compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "target": "es5",
 "sourceMap": true

第 5 步:如何使用 NPM 配置文件添加 grunt 包

现在我们需要添加一个 NPM 配置文件,用于添加 Grunt 包来运行我们的 JavaScript。

由于我们已将其创建为 Web 应用程序,因此 NPM 配置文件将位于我们的项目中。

默认情况下,我们无法查看我们的 NPM 配置文件。NPM 配置文件将以“package.JSON”命名。要从解决方案资源管理器中查看它,请单击“显示所有文件”

现在打开“package.JSON”文件。首先我们需要将名称更改为我们的项目解决方案名称并添加我们的 grunt 包。我们可以在下面的图片中看到代码。

在这里,我们已将名称更改为我们的解决方案名称,并添加了 Grunt 包。

{
  "name": "test",
  "version": "0.0.0",
  "private": true,
"devDependencies": {
    "grunt": "1.0.1",
    "grunt-contrib-copy": "1.0.0",
    "grunt-contrib-uglify": "1.0.1",
    "grunt-contrib-watch": "1.0.0",
    "grunt-ts": "5.5.1",
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

现在保存 package.json 文件,您应该能在 Dependencies/ npm 文件夹下看到一个 grunt 包,它将首先被恢复然后安装。

正在恢复

全部安装

第 6 步:配置 Grunt 文件。

Grunt 用于构建我们项目的所有客户端资源,如 JavaScript。

第一步是向我们的项目添加一个 Grunt 文件。右键单击我们的项目,然后选择 Grunt Configuration File,然后单击 Add。

创建文件后,现在我们需要编辑此文件以添加加载插件、配置插件和定义任务。

在我们的 Grunt 文件中,我们首先加载我们在 npm 中添加的插件。使用 loadNpmTask,我们加载 'grunt-contrib-copy'、'grunt-contrib-uglify'、'grunt-contrib-watch'

接下来,我们配置 grunt,将 app.js 文件添加到我们的 wwwroot 文件夹中。我们 Scripts 文件夹中的所有脚本文件结果都将添加到此 app.js 文件中。接下来,我们需要将所有脚本文件从 'node_modules/' 复制到我们的本地 js 文件夹。

watch 插件将用于检查 JavaScript 文件是否有任何更改,并使用所有新更改更新 app.js。

/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-ts');
    grunt.initConfig({
        ts:
        {
            base:
            {
                src: ['Scripts/app/boot.ts', 'Scripts/app/**/*.ts'],
                outDir: 'wwwroot/app',
                tsconfig: './tsconfig.json'
            }
        },
        uglify:
        {
            my_target:
            {
                files: [{
                    expand: true,
                    cwd: 'wwwroot/app',
                    src: ['**/*.js'],
                    dest: 'wwwroot/app'
                }]
            },
            options:
            {
                sourceMap: true
            }
        },
        // Copy all JS files from external libraries and required NPM packages to wwwroot/js  
        copy: {
            main: {
                files:
                     [{
                         expand: true,
                         flatten: true,
                         src: ['Scripts/js/**/*.js', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/angular2.dev.js'],
                         dest: 'wwwroot/js/',
                         filter: 'isFile'
                     }]
            }
        },
        // Watch specified files and define what to do upon file changes  
        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['ts', 'uglify', 'copy']
            }
        }
    });
    // Define the default task so it will launch all other tasks  
    grunt.registerTask('default', ['ts', 'uglify', 'copy', 'watch']);
};

第 7 步:添加依赖项以安装 Angular2 和所有其他文件

我们使用 NPM 在我们的 Web 应用程序中安装 Angular2。打开我们的 Package.JSON 文件并添加以下依赖项。

"dependencies": {
    "@angular/http": "2.0.0-rc.1",
    "angular2": "^2.0.0-beta.8",
    "angular2-jwt": "0.1.16",
    "angular2-meteor": "0.5.5",
    "cors": "2.7.1",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "tsd": "^0.6.5",
    "zone.js": "0.5.15"
  },

编辑后的 Package.json 文件将如下所示。

保存文件,然后等待几秒钟以完成所有依赖项的安装。

第 8 步:如何使用 TypeScript 文件创建我们的 Angular2 应用并引导

现在是时候创建我们的 Angular2 应用程序了。首先创建一个名为 Scripts 的文件夹。右键单击我们的项目,单击添加新文件夹,并将文件夹名称命名为“Scripts”。现在我们将在 Scripts 文件夹中创建我们的 TypeScript 文件。

要使用 Angular2,我们需要创建 2 个重要的 TypeScript 文件。

  1. 组件文件,我们在其中编写我们的 Angular 代码。
  2. 引导文件:运行我们的组件应用。

创建 App TypeScript 文件

右键单击 Scripts 文件夹,然后单击添加新项。选择 TypeScript File,并将文件名命名为 App.ts,然后单击 Add。

在 App.ts 文件中,我们有三个部分,第一个是

  1. import 部分
  2. 接下来是 component 部分
  3. 接下来是用于编写业务逻辑的类。

这里我们可以看到一个简单的基本单向绑定示例,用于在 h1 标签内显示欢迎消息。在这里。

  1. import 部分:首先我们导入 Angular2 文件以在我们的组件中使用,这里我们导入 http 以在我们的 Angular2 组件中使用 http 客户端,导入 NgFor 以使用循环并逐个绑定所有学生详细信息数组值,并且我们还从模型文件导入另一个名为 StudentMasters 的 TypeScript 导出类。
import { Component, Injectable} from 'angular2/core';
import { NgFor } from 'angular2/common';
import {Http, Headers, Response} from 'angular2/http';
import { StudentMasters } from './model';
import 'rxjs/Rx';

      2. 接下来是组件部分

在组件中,我们有选择器、指令和模板。选择器用于为此应用命名,在我们的 html 文件中,我们使用此选择器名称在我们的 html 页面中显示。在模板中,我们编写我们的代码。在模板中,我们使用 ngFOR 绑定 StudentMaster 详细信息。学生详细信息将加载到我们的导出类中,我们在其中编写所有业务逻辑和 http 函数以从 WEB API 加载数据。

@Component({
    selector: "my-app",
    directives: [NgFor],
    template: `
            <h1 style="color:#467813;">ASP.NET Core / Angular2 and WEB API Demo </h1>
<hr>
  <h2>A Simple demo made by : <span style="color:#8340AF;">{{myName}} </span> </h2>
  
<h2 style="color:#FF5733;"> Student Details retured from WEB API as JSON result  </h2>
 <h3 style="color:#C70039;">
   <ul>
      <li *ngFor="let std of student">
   <code> <span *ngFor="let stdArray of generateArray(std)"> {{stdArray}} </span> </code>
</li>
      
    </ul>
</h3>
              `,})

3. 导出类

这是我们执行所有业务逻辑和变量声明以供组件模板使用的主类。在此类中,我们创建了一个名为 getData() 的方法,在此方法中,我们获取 API 方法的结果并将结果绑定到 student 数组。在我们的组件模板中,我们将绑定来自此 student 数组的结果。

export class AppComponent {
    student: Array<StudentMasters> = [];
    myName: string;
    constructor(public http: Http) {
        this.myName = "Shanu";
        this.getData();
    }

    getData() {

        this.http.get('api/StudentMasters')
            .map((res: Response) => res.json())
            .subscribe(
            data => { this.student = data },
            err => console.error(err),
            () => console.log('done')

            );
    }
    // to generate the JSON object as array
    generateArray(obj) {
        return Object.keys(obj).map((key) => { return obj[key] });
    }
}

接下来,我们需要添加 boot.ts 文件来运行我们的应用程序。

创建 boot TypeScript 文件

右键单击 Scripts 文件夹,然后单击添加新项。选择 TypeScript File,并将文件名命名为 boot.ts,然后单击 Add。

在 boot.ts 文件中,我们添加以下代码。首先,我们导入 bootstrap 文件来加载和运行我们的 app 文件,并且我们还导入了我们的 app 组件。请注意,要导入我们的 app,我们需要提供与我们的 app typescript 文件中给出的类名相同的名称,并将我们的 app 路径从 '`./app`' 开始。接下来,我们通过在 bootstrap 中添加 app 名称 'bootstrap(myAppComponent);' 来运行我们的 app。

///<reference path="../node_modules/angular2/typings/browser.d.ts" />  

import {bootstrap} from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from "angular2/router";
import {HTTP_PROVIDERS, HTTP_BINDINGS} from "angular2/http";
import {AppComponent} from './app'

bootstrap(AppComponent, [HTTP_BINDINGS, HTTP_PROVIDERS]);

创建 model TypeScript 文件

右键单击 Scripts 文件夹,然后单击添加新项。选择 TypeScript File,并将文件名命名为 model.ts,然后单击 Add。

我们使用此 model typescript 文件来创建我们的 Studentmasters 模型,并声明我们在 MVC 模型中创建的所有公共属性。

export class StudentMasters {
    constructor(
        public StdID: number,
        public StdName: string,
        public Email: string,
        public Phone: string,
        public Address: string
    ) { }
}

第 9 步:创建 HTML 文件

接下来,我们需要创建我们的 html 页面来查看结果。要添加 HTML 文件,请右键单击 wwwroot 文件夹,单击添加新项,将名称命名为 index.html,然后单击 Add。

在 HTML 文件中替换以下代码。在这里,我们首先在 header 部分添加所有脚本引用文件,并在脚本中加载我们的 boot 文件来运行我们的应用程序。在 body 部分,我们使用组件选择器名称显示结果。在我们的 app 组件中,我们给选择器名称为“myapp1”。在此 HTML 中显示结果,我们添加的标签如下  <my-app>请稍候...</my-app>

<html>

<head>
    <title>ASP.NET Core: AngularJS 2 Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills -->
    <script src="/js/es6-shim.min.js"></script>
    <script src="/js/system-polyfills.js"></script>
    <!-- Angular2 libraries -->
    <script src="/js/angular2-polyfills.js"></script>
    <script src="/js/system.src.js"></script>
    <script src="/js/Rx.js"></script>
    <script src="/js/angular2.dev.js"></script>
    <script src="/js/router.dev.js"></script>
    <script src="/js/http.dev.js"></script>
    <!-- Bootstrap via SystemJS -->
    <script>

        System.config
        ({
            packages:
            {
                "app":
                {
                    defaultExtension: 'js'
                },
                'lib': { defaultExtension: 'js' }
            }
        });
        System.import('app/boot').then(null, console.error.bind(console));
    </script>
</head>

<body>
    <!-- Application PlaceHolder -->
    <my-app>Please wait...</my-app>

</body>

</html>

那么接下来,我们已经成功创建了我们的第一个 Angular2 和 Asp.Net Core 1.0 Web 应用程序,等等,我们还需要做一项尚未完成的工作来运行我们的应用程序?是的,我们需要运行我们的 Grunt 文件,以便在我们的 wwwroot scripts 文件夹中创建我们所有的脚本文件。

第 8 步:使用 Visual Studio Task Runner Explorer 运行 Grunt 文件

现在我们需要使用 Visual Studio 任务运行器运行 Grunt 文件。

要查看 Task Runner,请单击菜单 View-> Other Windows,->,然后单击 Task Runner

我们也可以通过在 Solution Explorer 中右键单击我们的 Gruntfile.js 并单击 Task Runner Explorer 来打开 Task Runner。

现在我们可以看到我们的任务运行器资源管理器。

单击 GruntFile.js 并单击左上角的刷新按钮。

现在我们可以看到所有的 GruntFile 都已添加。

右键单击别名任务下的默认值并单击“运行”。

现在我们的 Grunt 文件已在我们的项目中成功运行。当我们添加脚本文件时,我们可以看到在我们的 wwwroot 文件夹中将创建一个新的 app.js 文件。

运行程序

在这里,我们可以看到来自 WEB API 的所有数据都已使用 Angular2 绑定到我们的 HTML 页面。

历史

ShanuASPNETCoreAngular2WEBAPI.zip - > 2016-07-11

© . All rights reserved.