[转]Using MVC 6 And AngularJS 2 With .NET Core
本文转自:http://www.c-sharpcorner.com/article/using-mvc-6-and-angularjs-2-with-net-core/
In this article,
- Setup Environment.
- Overview on ASP.NET.
- Start with .NET Core 1.0.
- Explore Initial Template (Empty).
- How to Add MVC6.
- AngularJS2.
- Manage Client-side Dependencies.
- Use Package Manager (NPM).
- Use Task Runner.
- Bootstrapping, using Type Script
- Build & run Application
Setup Environment
Prerequisites: The following prerequisites are needed.
- Visual Studio 2015
- ASP.NET Core 1.0
Visual Studio 2015: If you already have a copy of Visual Studio 2015 installed, you may update Visual Studio 2015 with Update 3. Or Download Visual Studio Community 2015 for free.
.NET Core Downloads:
You may download one of these:
- .NET Core SDK (Software Development Kit/Command Line Interface) tools.
- .NET Core 1.0.0 - VS 2015 Tooling Preview 2 (Run apps with the .NET Core runtime).
We are all set to go. Before we dive into our main topic, let’s get an overview on ASP.NET.
Overview on ASP.NET
Let’s differentiate both.
.NET Framework
- Developed and run on Windows platform only.
- Built on the .NET Framework runtime.
- Supported (MVC, Web API & SignalR) Dependency Injection (DI).
- MVC & Web API Controller are separated.
.Net Core
- Open Source.
- Developed & run on Cross Platform.
- Built on the .NET Core runtime & also on .NET Framework.
- Facility of dynamic compilation.
- Built in Dependency Injection (DI).
- MVC & Web API Controller are unified, Inherited from same base class.
- Smart tooling (Bower, NPM, Grunt & Gulp).
- Command-line tools.
Start with .NET Core 1.0
Let’s create a new project with Visual Studio 2015 > File > New > Project.
Choose empty template and click OK.
Visual Studio will create a new project of ASP.NET Core empty project.
We will now explore all initial files one by one.
Explore Initial Template
Those marked from Solution Explorer are going to be explored, one by one.
First of all, we know about program.cs file. Let’s concentrate on it.
Program.cs: Here, we have sample piece of code. Let’s get explanation.
- 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() : Define the Web Server. ASP.NET Core supports hosting in IIS and IIS Express.
HTTP servers
- Microsoft.AspNetCore.Server.Kestrel (cross-platform)
- Microsoft.AspNetCore.Server.WebListener (Windows-only)
.UseContentRoot(Directory.GetCurrentDirectory()) : Application base path that specifies the path to the root directory of the Application. .UseIISIntegration(): For hosting in IIS and IIS Express. .UseStartup<Startup>() : Specifies the Startup class. .Build() : Build the IWebHost, which will host the app & manage incoming HTTP requests.
Startup.cs
This is the entry point of every .NET Core Application. It provides services, that the Application required.
- 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) {}
- }
- }
As you can see, there are two methods; one is ConfigureServices & another is Configure. In Configure method, three parameters are specified.
IApplicationBuilder defines a class, which provides the mechanisms to configure an Application's request.
We can add MVC (middleware) to the request pipeline by using “Use” extension method. Later, we will use it. ConfigureServices is an extension method, which is configured to use the several services.
Project.json: This is where our Application dependencies are listed i.e by name & version. This file also manages runtime, compilation settings. Dependencies: All Application dependencies can add new dependencies, if required, intellisense will help up to include with the name & version.
After saving changes, it will automatically restore the dependencies from 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"
- },
To uninstall, go to Solution explorer > right click on package > Uninstall package.
Tools: This section manages and lists command line tools. We can see IISIntegration.Tools is added by default, which is a tool that contains dotnet publish iis command for publishing the Application on IIS.
- "tools": {
- "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
- },
Frameworks: As we can see, initially our app is running on the .NET Core platform by default with the runtime.
- “netcoreapp1 .0”.
- "frameworks": {
- "netcoreapp1.0": {
- "imports": ["dotnet5.6", "portable-net45+win8"]
- }
- },
Build Options: Options, which are passed to the compiler while building the Application.
- "buildOptions": {
- "emitEntryPoint": true,
- "preserveCompilationContext": true
- },
RuntimeOptions: Manage Server garbage collection at Application runtime.
- "runtimeOptions": {
- "configProperties": {
- "System.GC.Server": true
- }
- },
PublishOptions: This defines the file/folder to include/exclude to/from the output folder, while publishing the Application.
- "publishOptions": {
- "include": ["wwwroot", "web.config"]
- },
Scripts: Scripts is an object type, which specifies that scripts run during building or publishing the Application.
- "scripts": {
- "postpublish": ["dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"]
- }
Add MVC6
It’s time to add MVC6. In .NET Core 1.0 MVC & Web API are unified, and become a single class, which inherits from the same base class.
Let’s add MVC Service to our Application. Open project.json to add new dependencies in it. In dependencies section, add two dependencies.
- "Microsoft.AspNetCore.Mvc": "1.0.0",
- "Microsoft.AspNetCore.StaticFiles": "1.0.0"
Click Save.
It will start restoring the packages automatically.
Now let’s add MVC (midleware) to request pipeline in Config method at startup class.
- 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?}");
- });
- }
In ConfigureServices method, we need to add framework Service. We have added services.AddMvc();
- public void ConfigureServices(IServiceCollection services) {
- services.AddMvc();
- }
MVC Folder Structure
Let’s add MVC folder structure to our sample Application. We have added view files in the views folder & MVC controller in Controllers folder like old MVC Application.
Here, you may notice that there is a new file in the views folder “_ViewImports.cshtml”. This file is responsible for setting up the namespaces, which can be accessed by the views in the project, which was previously done by the Web.config file in the views folder.
We are almost done. Let’s modify our view content with welcome message. Now, run the Application. You can see welcome message appears in the home page.
Output
AngularJS2
AngularJS2 is a modern Client end JavaScript Framework for the Application development. This JavaScript framework is totally new & written, based on TypeScript.
We will follow the steps, given below, to learn, how we install it to our Application,
- Manage Client-side Dependencies
- Use Package Manager (NPM).
- Use Task Runner.
- Bootstrapping using Type Script.
Client-side Dependencies: We need to add a JSON config file for Node Package Manager(NPM). Click add > New Item > Client- Side > npm Configuration File and click OK.
Open our newly added npm config file and modify the initial settings.
Package.json
- {
- "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"
- }
- }
In the dependencies section, we need to add AngularJS2 with other dependencies and they are for:
- Es6-shim is a library, which provides compatibility on old environment.
- Rxjs provides more modular file structure in a variety of formats.
- SystemJS enables System.import TypeScript files directly.
As you can see, there are two different type objects; one is dependencies, which are used for the production purposes & the other one is devDependencies for development related things, like gulp is to run different tasks.
Click save. It will restore automatically. Here, we have all our required packages in the Dependencies section.
- Manage html, css, js component
- Load minimal resources
- Load with flat dependencies
- Install dependencies recursively
- Load nested dependencies
- Manage NodeJS module



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']);
To run the task, right click on Gulp.json file to reload.
Right click on copy-all & click run.
Task run & finish.

Bootstrapping with 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 : Raise an error on the expressions and declarations with an implied ‘any’ type. noEmitOnError: Do not emit outputs, if any errors were reported. Target : Specify ECMAScript target version: ‘es5’ (default), ‘es5’, or ‘es6’. experimentalDecorators : Enables an experimental support for ES7 decorators.
Get more details on Compiler option here.
Create an app folder for .ts file in wwwroot folder.
In Solution Explorer, you may add the files, given below.
In main.ts code snippet, bootstrap AngularJS with importing the component.
- import {bootstrap} from 'angular2/platform/browser';
- import {AppComponent} from './app.component';
- import {enableProdMode} from 'angular2/core';
- enableProdMode();
- bootstrap(AppComponent);
Component: imports the Component function from Angular 2 library; use of import, app component class can be imported from other 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 View: It’s time to update our layout & linkup the library.
Now, we will add the reference to our layout page.
- <!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> }
One more thing to do is to enable the static file serving. Add this line to startup config method.
app.UseStaticFiles();
Build & run application
Finally, build & run the Application.
Output
Here, we can see our app is working with AngularJS2.
[转]Using MVC 6 And AngularJS 2 With .NET Core的更多相关文章
- 如何在 ASP.NET MVC 中集成 AngularJS(3)
今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...
- 如何在 ASP.NET MVC 中集成 AngularJS(2)
在如何在 ASP.NET MVC 中集成 AngularJS(1)中,我们介绍了 ASP.NET MVC 捆绑和压缩.应用程序版本自动刷新和工程构建等内容. 下面介绍如何在 ASP.NET MVC 中 ...
- 前端MVC学习总结——AngularJS验证、过滤器
前端MVC学习总结--AngularJS验证.过滤器 目录 一.验证 二.过滤器 2.1.内置过滤器 2.1.1.在模板中使用过滤器 2.1.2.在脚本中调用过滤函数 2.2.自定义过滤器 三.指令( ...
- 如何在 ASP.NET MVC 中集成 AngularJS(1)
介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 REST 的 Web API 服务.另外,还有最新的数据库技术.最新 ...
- [angularjs] MVC + Web API + AngularJs 搭建简单的 CURD 框架
MVC + Web API + AngularJs 搭建简单的 CURD 框架 GitHub 地址:https://github.com/liqingwen2015/Wen.MvcSinglePage ...
- ASP.NET MVC下使用AngularJs语言(六):获取下拉列表的value和Text
前面Insus.NET有在Angularjs实现DropDownList的下拉列表的功能.但是没有实现怎样获取下拉列表的value和text功能. 下面分别使用ng-click和ng-change来实 ...
- ASP.NET MVC下使用AngularJs语言(五):ng-selected
这次学习ng-selected语法,这个是为DropDownList下拉列表显示默认选项. 演示从下面步骤开始 1,新建一个model: 上面#14行代码的property,数据类型为bool.即是存 ...
- ASP.NET MVC下使用AngularJs语言(二):ng-click事件
程序用户交互,用户使用mouse点击,这是一个普通的功能. 在angularjs的铵钮点击命令是ng-click. 创建Angularjs的app使用前一篇<ASP.NET MVC下使用Angu ...
- ASP.NET MVC下使用AngularJs语言(一):Hello your name
新春节后,分享第一个教程. 是教一位新朋友全新学习ASP.NET MVC下使用AngularJs语言. 一,新建一个空的Web项目.使用NuGet下载AngularJs和jQuery.二,配置Bund ...
随机推荐
- ASP 缓存处理及URL 重写
1 缓存 1.1.1 <%--通过设置VaryByParam =" VaryByParam ="none" %> 1.1.2 <%--带参数缓存,只要包 ...
- Ray tracing performance benchmark
accel. avg size 3.14accel. avg depth 16.15accel. max size 8accel. max depth 20accel. GPIT 3.00 MB tr ...
- [Winter Vacation] 守护,守望
最近总是堕落......想好了,不如在百无聊赖之时写一些心底的话,让它们最终不归于尘土吧. 有了想要守护一个人的信念与想法,然而有没有资格却还没有人能够说清楚,下断言.这可真是可悲了,总不能笃定着对方 ...
- 快速启动工具Rulers 3.6
云盘下载:https://yunpan.cn/cq7mumZ5uzzgw (提取码:b16a) 能根据已经安装的所有软件的名称快速查询到并回车迅速打开1.Alt+空格无特效或者Alt键有特效控制显示和 ...
- 案例1-合并2个不同文件夹中的csv文件到另外一个目录,相同的文件名进行数据合并,不同的文件名直接移到新文件夹
发现在ubuntu和centos中有些命令还不一样,比如<<<可在centos中使用,但是ubuntu中不行 csv文件名以及格式如下 3669_20180121.csv 总笔数,2 ...
- 看完MJ讲解的单例后的个人总结
1.单例的介绍 单例是iOS常用的开发模式的一种. 2.什么是单例 单例就是一个类只创建一个对象,只分配一次内存空间. 3.单例的应用场景 1)系统的单例: [UIApplication share ...
- Flink学习笔记:Operators之CoGroup及Join操作
本文为<Flink大数据项目实战>学习笔记,想通过视频系统学习Flink这个最火爆的大数据计算框架的同学,推荐学习课程: Flink大数据项目实战:http://t.cn/EJtKhaz ...
- POJ2259 Team Queue (JAVA)
第一次TLE,对每个group重新设置Queue中定位,定位到每个group的最后一个元素,但WA 经过检查,DEQUEUE时没有根据情况重新计算group,插入时没有根据情况重新给last赋值 贴A ...
- C. Ayoub and Lost Array Round #533 (Div. 2) 【DP】
一.题面 链接 二.分析 关于这题,两个点. 第一个点,是需要能够分析出$[L,R]$区间的3的余数的个数. 首先,可以得到,$[L,R]$区间内共有$(R-L+1)$个数. 设定余数为0,1,2的为 ...
- 线性代数与simplex
线性方程组: \(i:1-n\) \(j:1-m\) \({\begin{cases}a_{11}x_1+a_{12}x_2+a_{13}x_3+\cdots+a_{1n}x_n=b_1\\a_{21 ...