ASP.NET Core上的Angular SPA

时间:2017-03-24 00:36:01

标签: angular asp.net-core

我从这里读到了很多关于它的文件。但最后在尝试自己的部分我想念一些东西。这是我的情景。

我正在研究ASP.NET核心模板。从它开始:

文件:Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SpaServices.Webpack;
using SMT000000.Data;
using SMT000000.Models;
using SMT000000.Services;

namespace SMT000000
{
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, 
    reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
    optional: true);

        if (env.IsDevelopment())
        {
            builder.AddUserSecrets<Startup>();
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
    Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "SPA", action = "Index" });
        });
    }
}
}

然后我添加了一个简单的控制器,其中的视图由不同的布局控制。

SPAController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace SMT000000.Controllers
{
    public class SPAController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}

_ViewStart.cshtml

@{
Layout=_LayoutSPA.cshtml
}

_LayoutSPA.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - SPA LAYOUT</title>
    <base href="/" />
    <link rel="stylesheet" href="~/dist/vendor.css" asp-append-
version="true" />
</head>
<body>
    @RenderBody()

    @RenderSection("scripts", required: false)
</body>
</html>

然后我添加了package.json,tsconfig.json和webpack.config.js来处理Angular 2部分的webpack。

 {
"name": "SMT000000",
"version": "0.0.0",
"scripts": {
 "test": "karma start ClientApp/test/karma.conf.js"
},
"dependencies": {
 "@angular/common": "^2.4.5",
 "@angular/compiler": "^2.4.5",
 "@angular/core": "^2.4.5",
 "@angular/forms": "^2.4.5",
 "@angular/http": "^2.4.5",
 "@angular/platform-browser": "^2.4.5",
 "@angular/platform-browser-dynamic": "^2.4.5",
 "@angular/platform-server": "^2.4.5",
 "@angular/router": "^3.4.5",
 "@types/node": "^6.0.42",
 "angular2-platform-node": "~2.0.11",
 "angular2-template-loader": "^0.6.2",
 "angular2-universal": "^2.1.0-rc.1",
 "angular2-universal-patch": "^0.2.1",
 "angular2-universal-polyfills": "^2.1.0-rc.1",
 "aspnet-prerendering": "^2.0.0",
 "aspnet-webpack": "^1.0.17",
 "awesome-typescript-loader": "^3.0.0",
 "bootstrap": "^3.3.7",
 "css": "^2.2.1",
 "css-loader": "^0.25.0",
 "es6-shim": "^0.35.1",
 "event-source-polyfill": "^0.0.7",
 "expose-loader": "^0.7.1",
 "extract-text-webpack-plugin": "^2.0.0-rc",
 "file-loader": "^0.9.0",
 "html-loader": "^0.4.4",
 "isomorphic-fetch": "^2.2.1",
 "jquery": "^2.2.1",
 "json-loader": "^0.5.4",
 "preboot": "^4.5.2",
 "raw-loader": "^0.5.1",
 "rxjs": "^5.0.1",
 "style-loader": "^0.13.1",
 "to-string-loader": "^1.1.5",
 "typescript": "^2.2.1",
 "url-loader": "^0.5.7",
 "webpack": "^2.2.0",
 "webpack-hot-middleware": "^2.12.2",
 "webpack-merge": "^0.14.1",
 "zone.js": "^0.7.8"
  },
   "devDependencies": {
   "@types/chai": "^3.4.34",
   "@types/jasmine": "^2.5.37",
   "chai": "^3.5.0",
   "jasmine-core": "^2.5.2",
   "karma": "^1.3.0",
   "karma-chai": "^0.1.0",
   "karma-chrome-launcher": "^2.0.0",
   "karma-cli": "^1.0.1",
   "karma-jasmine": "^1.0.2",
   "karma-webpack": "^1.8.0"
  }
}

tsconfig.json

    {
 "compilerOptions": {
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node" ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {

const isDevBuild = !(env && env.prod);
const sharedConfig = {
    stats: { modules: false },
    context: __dirname,
    resolve: { extensions: [ '.js', '.ts' ] },
    output: {
        filename: '[name].js',
        publicPath: '/dist/' // Webpack dev middleware, if enabled, handles 
requests for this URL prefix
    },
    module: {
        rules: [
            { test: /\.ts$/, include: /ClientAppSPA/, use: ['awesome-
typescript-loader?silent=true', 'angular2-template-loader'] },
            { test: /\.html$/, use: 'html-loader?minimize=false' },
            { test: /\.css$/, use: ['to-string-loader', 'css-loader'] },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 
 'url-loader?limit=25000' }
        ]
    },
    plugins: [new CheckerPlugin()]
};

// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './ClientAppSPA/boot-client.ts' },
    output: { path: path.join(__dirname, clientBundleOutputDir) },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [

        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map', 
            moduleFilenameTemplate: path.relative(clientBundleOutputDir, 
'[resourcePath]') 
        })
    ] : [

        new webpack.optimize.UglifyJsPlugin()
    ])
});


const serverBundleConfig = merge(sharedConfig, {
    resolve: { mainFields: ['main'] },
    entry: { 'main-server': './ClientAppSPA/boot-server.ts' },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./ClientAppSPA/dist/vendor-manifest.json'),
            sourceType: 'commonjs2',
            name: './vendor'
        })
    ],
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './ClientAppSPA/dist')
    },
    target: 'node',
    devtool: 'inline-source-map'
});

return [clientBundleConfig, serverBundleConfig];
};

最后,我渲染的视图是:

    @{
    ViewData["Title"] = "Home Page";
}

<app asp-prerender-module="ClientAppSPA/dist/main-server">Loading...</app>

<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}

项目树:

https://drive.google.com/file/d/0By6uV1HGsProVGRLQmczbVZ1d0U/view?usp=sharing

“The Thing”正在“工作”但是如果我将模板作为html文件而不是组件中的含义,那么我首先遇到加载角度组件的问题。 (我认为错过的路线在那里)但是试图使用implicits抛出下一个异常。我觉得它作为文件从未准备好。我知道我做得不好但是练习。如果有人可以指导我。欢呼声。

Exception

2 个答案:

答案 0 :(得分:0)

我正在使用ASP.NET Core处理Angular 2(使用Webpack构建)但使用不同的方法。我没有像你一样使用Razor,而是返回静态index.html文件的内容:

public IActionResult Index()
{
    return Content(GetContent(), new MediaTypeHeaderValue("text/html"));
}

Webpack配置为将构建的文件输出到 wwwroot 而不是 dist 。当然,您可以向Webpack添加构建步骤,以将内容从 dist 复制到 wwwroot

答案 1 :(得分:0)

我们想要使用角度cli,所以我采取了不同的方法。

可在此处找到项目:https://github.com/wickdninja/DotNetCoreAngular2Demo

ASP.NET Core / Angular 2通过CLI快速入门

声明

本指南是使用以下版本创建的,并未提供与任何其他版本兼容的保证。

angular-cli: 1.0.0-beta.28.3
node: 7.4.0
os: darwin x64
@angular/common: 2.4.6
@angular/compiler: 2.4.6
@angular/core: 2.4.6
@angular/forms: 2.4.6
@angular/http: 2.4.6
@angular/platform-browser: 2.4.6
@angular/platform-browser-dynamic: 2.4.6
@angular/router: 3.4.6
@angular/compiler-cli: 2.4.6

安装项目依赖项

  • ASP.NET Core
  • NodeJS
  • Yoeman
    • $ npm i -g yo
  • ASP.NET核心生成器
    • $ npm i -g generator-aspnet
  • Angular CLI
    • $ npm i -g angular-cli

生成项目

  • $ yo aspnet
    • 选择Web Api项目
    • 名称申请DemoApp
    • $ cd DemoApp

服务器设置

  • 打开project.json

    • 从编译中排除node_modules
    • 将以下内容添加到"buildOptions"

    "compile": { "exclude": [ "node_modules" ] }

    • 添加StaticFiles依赖
    • "Microsoft.AspNetCore.StaticFiles": "1.0.0"添加到dependencies
  • 恢复依赖项
    • $ dotnet restore
  • 配置服务器以处理api路由和客户端路由

    • 打开Startup.cs
    • 找到Configure方法添加以下内容

      • 配置CORS

      app.UseCors(cors => cors .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() );

      • 将请求路由到客户端spa的root

      app.Use(async (context, next) => { await next(); if (context.Response.StatusCode == 404) { Console.WriteLine("passing to client"); context.Request.Path = "/"; await next(); } });

      • 启用静态文件(不允许目录浏览)

      app.UseFileServer(enableDirectoryBrowsing: false);

      • 设置API的路径

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

  • 通过构建服务器验证更改

    • $ dotnet build

客户端设置

  • 使用角度CLI创建一个新的角度2应用程序
    • $ ng new DemoApp
  • 将角度应用移动到项目的根目录
    • $ mv DemoApp/* .
    • 此命令会移动除“点文件”
    • 之外的所有内容
    • 移动.editorconfig
    • $ mv DemoApp/.editorconfig .
    • 移动git repo
    • $ mv DemoApp/.git .
    • DemoApp/.gitignore的内容复制到./gitignore
    • 查找并取消注释#wwwroot
      • 删除#字符
    • 删除角度生成的应用根
    • $ rm -rf DemoApp
  • 配置Angular CLI构建输出
    • 打开angular-cli.json
    • 更新outDir
      • "outDir": "wwwroot"
  • 测试客户端应用构建
    • $ ng build

构建脚本

  • 打开project.json

    • scripts替换为以下

    "scripts": { "ng": "ng", "prerestore": "npm install", "restore": "dotnet restore", "postrestore": "npm run build", "prestart": "npm run restore", "start": "dotnet run", "client": "ng serve", "lint": "tslint \"src/**/*.ts\"", "test": "ng test", "pree2e": "webdriver-manager update --standalone false --gecko false", "e2e": "protractor", "clean": "rimraf -- wwwroot", "postclean": "ng build", "prebuild": "npm run clean", "build": "dotnet build", "clean:prod": "rimraf -- wwwroot", "postclean:prod": "ng build --prod", "prebuild:prod": "npm run clean:prod", "build:prod": "dotnet publish -c release" }

运行应用

  • $ npm start
    • 等待服务器启动
    • Now listening on: http://localhost:5000
    • 验证客户端应用程序是否正常工作
    • 打开浏览器并导航至http://localhost:5000
      • 来自AppComponent的app works!文字显示在屏幕上
    • 验证API正常运行
    • 导航至http://localhost://5000/api/values
      • 响应应为以下JSON ["value1","value2"]