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

.NET CORE 1.0, MVC6 & ANGULARJS2 - 入门

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (29投票s)

2016 年 8 月 1 日

CPOL

7分钟阅读

viewsIcon

57157

downloadIcon

1269

在本文中,我们将探讨 .Net Core,了解如何使用 MVC6 和 AngularJS2,以及如何使用 Node 包管理器 (NPM) 管理客户端依赖项。

目录

  1. 设置环境
  2. ASP.Net 概述
  3. 开始使用 .Net Core 1.0。
  4. 探索初始模板 (Empty)
  5. 如何添加 MVC6
  6. AngularJS2
    1. 管理客户端依赖项
    2. 使用包管理器 (NPM)。
    3. 使用任务运行器
    4. 使用 Type Script 进行引导
  7. 构建并运行应用程序

1. 设置环境

先决条件:需要以下先决条件。

  1. Visual Studio 2015
  2. ASP.NET Core 1.0

Visual Studio 2015:如果您已安装 Visual Studio 2015,则可以使用 Update 3 更新 Visual Studio 2015。

或者

免费下载 Visual Studio Community 2015。

.NET Core 下载

您可以下载以下之一

  1. .NET Core SDK (软件开发工具包/命令行接口) 工具
  2. .NET Core 1.0.0 - VS 2015 Tooling Preview 2 (运行具有 .NET Core 运行时的应用程序)

我们已经准备就绪。在深入探讨我们的主题之前,让我们先回顾一下 ASP.Net。

2. ASP.Net 概述

让我们区分两者。

.Net Framework

  1. 仅在 Windows 平台开发和运行。
  2. 基于 .NET Framework 运行时构建。
  3. 支持 (MVC、Web API 和 SignalR) 依赖项注入 (DI)。
  4. MVC 和 Web Api 控制器是分开的。

 .Net Core

  1. 开源。
  2. 在跨平台开发和运行。
  3. 基于 .NET Core 运行时以及 .NET Framework 构建。
  4. 动态编译功能。
  5. 内置依赖项注入 (DI)。
  6. MVC 和 Web Api 控制器统一,继承自同一个基类。
  7. 智能工具 (Bower、NPM、Grunt 和 Gulp)。
  8. 命令行工具。

3. 开始使用 .Net Core 1.0

让我们使用 Visual Studio 2015 > File > New > Project 创建一个新项目

选择 Empty 模板,然后单击 > OK。

Visual Studio 将创建一个新的 ASP.Net Core 空项目。

现在我们将逐一探索所有初始文件。

4. 探索初始模板

在解决方案资源管理器中标记的部分将逐一探索。

首先,我们了解 program.cs 文件。好的,让我们专注于它。

Program.cs:这里有一段示例代码,让我们来解释一下。

namespace CoreMVCAngular
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

.UseKestrel():定义 Web 服务器。ASP.NET Core 支持在 IIS 和 IIS Express 中托管。

HTTP 服务器

  1. Microsoft.AspNetCore.Server.Kestrel (跨平台)
  2. Microsoft.AspNetCore.Server.WebListener (仅限 Windows)

.UseContentRoot(Directory.GetCurrentDirectory()):应用程序根目录,指定应用程序根目录的路径。

.UseIISIntegration():用于在 IIS 和 IIS Express 中托管。

.UseStartup<Startup>():指定 Startup 类。

.Build():构建将托管应用程序并管理传入 HTTP 请求的 IWebHost。

Startup.cs:这是每个 .Net Core 应用程序的入口点,提供应用程序所需的各种服务。

namespace CoreMVCAngular
{
    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 http://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, ILoggerFactory loggerFactory)
        {
            
        }
    }
}

如您所见,有两个方法:ConfigureServices 和 Configure。在 Configure 方法中,指定了三个参数。

IApplicationBuilder 定义了一个提供配置应用程序请求机制的类。

我们可以通过使用“Use”扩展方法将 MVC (中间件) 添加到请求管道,稍后我们将使用它。

ConfigureServices 是一个公共方法,用于配置使用各种服务。

Project.json:这是列出应用程序依赖项(名称和版本)的地方。此文件还管理运行时和编译设置。

Dependencies:所有应用程序依赖项都在这里,如果需要,我们可以添加新的依赖项,Intellisense 将帮助我们包含名称和版本。

保存更改后,它将自动从 NuGET 还原依赖项。

这是我更改的代码片段。

"dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",

    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0"
  },

要卸载,请转到解决方案资源管理器 > 右键单击包 > 卸载包

Tools:此部分管理和列出命令行工具,我们可以看到默认添加了 IISIntegration.Tools,这是一个包含 dotnet publish iis 命令用于将应用程序发布到 IIS 的工具。

"tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

Frameworks:正如我们所见,最初我们的应用程序默认运行在 .NET Core 平台上,具有运行时 Code

"frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

Build Options:在构建应用程序时传递给编译器的选项。

"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

RuntimeOptions:在应用程序运行时管理服务器垃圾回收。

"runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

PublishOptions:这定义了在发布应用程序时要包含/排除到输出文件夹或从输出文件夹排除的文件/文件夹。

"publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

Scripts:Scripts 是对象类型,指定在构建或发布应用程序期间要运行的脚本。

"scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }

5. 添加 MVC6

现在是时候添加 MVC6 了。在 .NET Core 1.0 中,MVC 和 Webapi 已统一,成为一个类,继承自同一个基类。

让我们向应用程序添加 MVC 服务。打开 project.json 以在其中添加新依赖项。在 dependencies 部分添加两个依赖项。

"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0" //Serving static file

单击“保存”。

它将开始自动还原包。

现在,让我们在 startup 类的 Config 方法中将 MVC (中间件) 添加到请求管道。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    //app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

在 ConfigureServices 方法中,我们需要添加框架服务。我们已添加 services.AddMvc();

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

MVC 文件夹结构: 

让我们向我们的示例应用程序添加 MVC 文件夹结构。我们已将视图文件添加到 views 文件夹,并将 MVC 控制器添加到 Controllers 文件夹,就像旧的 MVC 应用程序一样。

您可能会注意到 views 文件夹中有一个新文件 "_ViewImports.cshtml",该文件负责设置项目中视图可以访问的命名空间,这以前是在 views 文件夹中的 web.config 文件中完成的。

我们几乎完成了。让我们修改视图内容以显示欢迎消息。现在运行应用程序,您可以看到欢迎消息显示在主页上。

输出

6. AngularJS2

AngularJS2 是一个现代的客户端 JavaScript 框架,用于应用程序开发。这个 JavaScript 框架是全新的,并且基于 TypeScript 编写。

我们将按照以下步骤学习如何将其安装到我们的应用程序中

  1. 管理客户端依赖项
  2. 使用包管理器 (NPM)。
  3. 使用任务运行器
  4. 使用 Type Script 进行引导

客户端依赖项:我们需要为 Node 包管理器 (NPM) 添加一个 json 配置文件。单击 Add > New Item > Client- Side > npm Configuration File,然后单击 OK。

打开我们新添加的 npm 配置文件并修改初始设置。

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "Dependencies": {
    "angular2": "2.0.0-beta.9",
    "systemjs": "0.19.24",
    "es6-shim": "^0.33.3",
    "rxjs": "5.0.0-beta.2"
  },
  "devDependencies": {
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

在 dependencies 部分,我们需要添加 AngularJS2 以及其他依赖项,它们的作用是:

  1. Es6-shim:这是一个库,在旧环境中提供兼容性。
  2. Rxjs:以各种格式提供更模块化的文件结构。
  3. SystemJS:允许直接导入 System.import TypeScript 文件。

正如您所见,有两种不同的对象类型:一种是用于生产目的的 dependencies,另一种是用于开发相关的 devDependencies,例如 gulp 用于运行不同的任务。

单击保存,它将自动还原。在这里,我们在 Dependencies 部分拥有所有必需的包。

在此应用程序中,我们添加了另一个包管理器 Bower,单击 Add > New Item > Client- Side > Bower Configuration File,然后单击 OK。

与 NPM 相比,

鲍尔

  1. 管理 html、css、js 组件
  2. 加载最少的资源
  3. 使用扁平化依赖项加载

NPM

  1. 递归安装依赖项
  2. 加载嵌套依赖项
  3. 管理 NodeJS 模块

打开配置文件,然后在 dependencies 部分添加所需的依赖项及特定版本。

编辑后保存 JSON 文件,它将自动在我们的项目中还原该包。在这里,您可以看到我们通过 Bower 包管理器添加了 Jquery 和 Bootstrap 包。

现在,让我们添加一个 gulp 配置文件来运行任务。单击 Add > New Item > Client- Side,然后选择 gulp json 文件进行包含。

Gulp.json

/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

"use strict";

var gulp = require("gulp");
var root_path = { webroot: "./wwwroot/" };

//library source
root_path.nmSrc = "./node_modules/";

//library destination
root_path.package_lib = root_path.webroot + "lib-npm/";

gulp.task("copy-systemjs", function () {
    return gulp.src(root_path.nmSrc + '/systemjs/dist/**/*.*', {
        base: root_path.nmSrc + '/systemjs/dist/'
    }).pipe(gulp.dest(root_path.package_lib + '/systemjs/'));
});

gulp.task("copy-angular2", function () {
    return gulp.src(root_path.nmSrc + '/angular2/bundles/**/*.js', {
        base: root_path.nmSrc + '/angular2/bundles/'
    }).pipe(gulp.dest(root_path.package_lib + '/angular2/'));
});

gulp.task("copy-es6-shim", function () {
    return gulp.src(root_path.nmSrc + '/es6-shim/es6-sh*', {
        base: root_path.nmSrc + '/es6-shim/'
    }).pipe(gulp.dest(root_path.package_lib + '/es6-shim/'));
});

gulp.task("copy-rxjs", function () {
    return gulp.src(root_path.nmSrc + '/rxjs/bundles/*.*', {
        base: root_path.nmSrc + '/rxjs/bundles/'
    }).pipe(gulp.dest(root_path.package_lib + '/rxjs/'));
});

gulp.task("copy-all", ["copy-rxjs", 'copy-angular2', 'copy-systemjs', 'copy-es6-shim']);

要运行任务,请右键单击 Gulp.json 文件,然后选择 reload。

右键单击 copy-all,然后单击 Run。

任务已运行并完成,正如您所见。

在解决方案资源管理器中,所有必需的包都已复制。我们还需要放置 es6-shim 的类型定义 (typing 文件夹),否则会报“Cannot find name 'Promise'”的错误。

使用 TypeScript 进行引导

Tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",

    //add this to compile app component
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "system",
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib"
  ]
}

noImplicitAny:当表达式和声明具有隐含的 'any' 类型时,引发错误。

noEmitOnError:如果报告了任何错误,则不发出输出。

Target:指定 ECMAScript 目标版本:“es5” (默认)、“es5” 或“es6”。

experimentalDecorators:启用 ES7 装饰器的实验性支持。

在此处获取有关编译器选项的更多详细信息:here

在 wwwroot 文件夹中为 .ts 文件创建一个 app 文件夹。

在解决方案资源管理器中,您可以按如下方式添加文件。

在 main.ts 中,代码片段通过导入组件来引导 AngularJS。

import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {enableProdMode} from 'angular2/core';

enableProdMode();
bootstrap(AppComponent);

Component:从 Angular 2 库导入 Component 函数,“export”的使用意味着 app component 类可以从其他组件导入。

import {Component} from 'angular2/core';

@Component({
    selector: 'core-app',
    template: '<h3>Welcome to .NET Core 1.0 + MVC6 + Angular 2</h3>'
})
export class AppComponent { }

MVC 视图:现在是时候更新我们的布局并链接库了。

现在我们将向 布局页面 添加引用。

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

    <script src="~/lib-npm/es6-shim/es6-shim.js"></script>
    <script src="~/lib-npm/angular2/angular2-polyfills.js"></script>
    <script src="~/lib-npm/systemjs/system.src.js"></script>
    <script src="~/lib-npm/rxjs/Rx.js"></script>
    <script src="~/lib-npm/angular2/angular2.js"></script>
</head>
<body>
    <div>
        @RenderBody()
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>

Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}
<core-app>
    <div>
        <p><img src="~/img/ajax_small.gif" />  Please wait ...</p>
    </div>
</core-app>

@section Scripts {
    <script>
        System.config({ packages: { 'app': { defaultExtension: 'js' } }, });
        System.import('app/main').then(null, console.error.bind(console));
    </script>
}

还有一件事要做是启用静态文件服务。将此行添加到 startup 配置方法中。

app.UseStaticFiles();

7. 构建并运行应用程序

最后构建并运行应用程序

在这里,我们可以看到我们的应用程序正在使用 AngularJS2 工作

希望这对您有所帮助 :)

© . All rights reserved.