Angular ASP.NET内核上的角度SPA
我从这里读了很多关于这件事的文件。但最后,在为自己努力的过程中,我错过了一些东西。这是我的设想 我正在使用ASP.NET核心模板。从它开始: 文件:Startup.csAngular ASP.NET内核上的角度SPA,angular,asp.net-core,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.Hosti
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" });
});
}
}
}
_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>
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>
}
@{
ViewData[“Title”]=“主页”;
}
“这个东西”是“工作”的,但首先我在加载角度组件时遇到了问题,如果我将模板作为html文件,而不是隐式加载到组件中。(我认为有一条路线错过了)但尝试使用隐式将引发下一个异常。我觉得作为文件,它从来没有准备好。我知道我做得不好,但在练习。如果有人能指引我。干杯
我正在使用ASP.NET内核开发Angular 2(使用Webpack构建),但方法不同。我没有像您现在这样使用Razor,而是返回static index.html文件的内容:
public IActionResult Index()
{
return Content(GetContent(), new MediaTypeHeaderValue("text/html"));
}
Webpack配置为将生成的文件输出到wwwroot而不是dist。当然,您可以将生成步骤添加到Webpack,以将内容从dist复制到wwwroot。我们希望使用angular cli,因此我采用了不同的方法
项目可在此处找到:
ASP.NET Core/Angular 2通过CLI快速入门
免责声明
本指南使用以下版本创建,不保证与任何其他版本的兼容性。
安装项目依赖项
- 尤曼
$npm i-g yo
- ASP.NET核心生成器
$npm i-g发生器aspnet
- 角型CLI
$npm i-g angular cli
生成项目
$yo aspnet
- 选择WebAPI项目
- 名称应用程序
DemoApp
$cd-DemoApp
服务器设置
- openproject.json
- 从编译中排除节点模块
- 将以下内容添加到
“构建选项”
“编译”:{
“排除”:[
“节点_模块”
]
}
- 添加静态文件依赖项
- 将
Microsoft.AspNetCore.StaticFiles:“1.0.0”
添加到依赖项中
- 恢复依赖项
$dotnet restore
- 配置服务器以处理api路由和客户端路由
- 打开
Startup.cs
- 找到
Configure
方法并将以下内容添加到其中
- 配置CORS
app.UseCors(cors=>
科尔斯
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
);
- 将客户端spa的请求路由到root
应用程序使用(异步(上下文,下一步)=>
{
等待下一个();
if(context.Response.StatusCode==404)
{
Console.WriteLine(“传递给客户”);
context.Request.Path=“/”;
等待下一个();
}
});
- 启用静态文件(不允许目录浏览)
app.UseFileServer(enableDirectoryBrowsing:false)代码>
- 设置API的路由
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“api”,
模板:“api/{controller=Version}/{action=Index}/{id?}”);
});
- 通过生成服务器验证更改
$dotnet build
客户端设置
- 使用angular CLI创建新的angular 2应用程序
$ng新DemoApp
- 将angular应用程序移动到项目的根目录
$mv DemoApp/*。
- 此命令移动除“点文件”以外的所有内容
- 移动
.editorconfig
$mv DemoApp/.editorconfig.
- 移动吉特回购
$mv DemoApp/.git.
- 将
DemoApp/.gitignore
的内容复制到/gitignore
- 查找并取消注释
#wwwroot
- 删除
#
字符
- 删除生成的应用程序根
$rm-rf DemoApp
- 配置客户端生成输出
- 打开
angular cli.json
- 更新
outDir
“outDir”:“wwwroot”
- 测试客户端应用程序构建
$ng构建
构建脚本
- 打开
project.json
- 将
脚本
替换为以下内容
“脚本”:{
“ng”:“ng”,
“预还原”:“npm安装”,
“还原”:“dotnet还原”,
“后期还原”:“npm运行生成”,
“预启动”:“npm运行还原”,
“开始”:“dotnet运行”,
“客户”:“ng服务”,
“lint”:“tslint\”src/***.ts\”,
“测试”:“ng测试”,
“pree2e”:“webdriver管理器更新--独立错误--gecko错误”,
“e2e”:“量角器”,
“干净”:“rimraf--wwwroot”,
“后清洁”:“ng构建”,
“预构建”:“npm运行清洁”,
“构建”:“dotnet构建”,
“清洁:产品”:“rimraf--wwwroot”,
“后清洁:产品”:“ng构建——产品”,
“预构建:产品”:“npm运行清理:产品”,
“build:prod”:“dotnet发布-c版本”
}
运行应用程序
$npm开始
- 等待服务器启动
正在收听:http://localhost:5000
- 验证客户端应用程序是否正常工作
- 打开浏览器并导航到
http://localhost:5000
- 注意
应用程序工作屏幕上显示来自AppComponent的代码>文本
- 验证API是否正常工作
- 导航到
http://localhost://5000/api/values
- 响应应该是以下JSON
[“value1”、“value2”]
@{
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>
}
public IActionResult Index()
{
return Content(GetContent(), new MediaTypeHeaderValue("text/html"));
}
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