Angular 角度模板上的.NET core 2.1 base href标记
我正在为我们的团队构建一个模板,该模板位于最新版本Core 2.1中包含的.NET Core 2.1+Angular 5模板之上,我们将应用程序部署到虚拟文件夹中,例如/it/myapp或/aa/myotherapp 在2.0模板上,base href属性将自动设置,我假设是因为它是用razor构建的,如下所示:Angular 角度模板上的.NET core 2.1 base href标记,angular,single-page-application,asp.net-core-2.1,Angular,Single Page Application,Asp.net Core 2.1,我正在为我们的团队构建一个模板,该模板位于最新版本Core 2.1中包含的.NET Core 2.1+Angular 5模板之上,我们将应用程序部署到虚拟文件夹中,例如/it/myapp或/aa/myotherapp 在2.0模板上,base href属性将自动设置,我假设是因为它是用razor构建的,如下所示: <base href="~/" /> 但是,对于2.1模板来说,情况并非如此,我假设这是因为该模板实际上只使用静态文件,而使用了新的app.UseSpa() 关于如何
<base href="~/" />
但是,对于2.1模板来说,情况并非如此,我假设这是因为该模板实际上只使用静态文件,而使用了新的app.UseSpa()
关于如何自动填充base href标记,有什么想法吗
谢谢是的,我知道这是一个老问题,但我希望这对其他人有更多帮助。答案是关于Angular 6和.NET Core 2.1。建议:解释有点大(对不起) 在Core2.1中,我们有一个典型的Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
spa.Options.DefaultPage = $"/index.html";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
重要的部分是
spa.UseAngularCliServer(npmScript: "start");
这将告诉.NET使用package.json中定义的脚本
{
"name": "client-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --base-href=/ --serve-path=/", //<--this line
"build": "ng build",
...
},
....
}
查看如何将this.\u options.baseHref添加到脚本中
实际上,在构造函数中我们没有baseHref,这是因为我们必须更改browser.js文件
在
还有一步。当我们在index.html中使用javascript编写基本标记时,我们不希望添加此标记。为此,我们必须更改的唯一一件事是对index-html-webpack-plugin.js中的行进行注释
class IndexHtmlWebpackPlugin {
constructor(options) {
this._options = Object.assign({ input: 'index.html', output: 'index.html', entrypoints: ['polyfills', 'main'], sri: false }, options);
}
apply(compiler) {
....
const scriptElements = treeAdapter.createDocumentFragment();
for (const script of scripts) {
const attrs = [
{ name: 'type', value: 'text/javascript' },
//change the line
//{ name: 'src', value: (this._options.deployUrl || '') + script },
//by
{ name: 'src', value: (this._options.baseHref)+(this._options.deployUrl || '') + script },
];
if (this._options.sri) {
const content = compilation.assets[script].source();
attrs.push(...this._generateSriAttributes(content));
}
const element = treeAdapter.createElement('script', undefined, attrs);
treeAdapter.appendChild(scriptElements, element);
}
// Adjust base href if specified
if (typeof this._options.baseHref == 'string') {
let baseElement;
for (const headChild of headElement.childNodes) {
if (headChild.tagName === 'base') {
baseElement = headChild;
}
}
const baseFragment = treeAdapter.createDocumentFragment();
if (!baseElement) {
baseElement = treeAdapter.createElement('base', undefined, [
{ name: 'href', value: this._options.baseHref },
]);
//coment the two lines below
// treeAdapter.appendChild(baseFragment, baseElement);
// indexSource.insert(headElement.__location.startTag.endOffset + 1, parse5.serialize(baseFragment, { treeAdapter }));
}
就这些
还有两个有趣的问题
当我们使用javascript创建base标记时,我们需要调整base。否则,如果我们刷新页面,我们的基本href会改变,如果我们在主页上,我们的url将类似于http://www.dominio.com/ <script>
var items = document.location.href.split('/');
while (items.length>4)
items.pop();
document.write('<base href="' + items.join('/') + '" />');
</script>
更新
使用java脚本添加选项卡库这是一个非常糟糕的解决方法。更好地使用基本参考提供程序
import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}
在
npmi
之后更改node_模块中的网页文件听起来不是个好主意。非常肮脏和脆弱的黑客,它将在下一个npmi
中被覆盖,并且在源代码管理中不可持久
plugins: extraPlugins.concat([
new index_html_webpack_plugin_1.IndexHtmlWebpackPlugin({
input: path.resolve(root, buildOptions.index),
output: path.basename(buildOptions.index),
baseHref: buildOptions.baseHref,
entrypoints: package_chunk_sort_1.generateEntryPoints(buildOptions),
deployUrl: buildOptions.deployUrl,
//we add this line
servePath: buildOptions.servePath,
sri: buildOptions.subresourceIntegrity,
}),
]),
// Adjust base href if specified
if (typeof this._options.baseHref == 'string') {
let baseElement;
for (const headChild of headElement.childNodes) {
if (headChild.tagName === 'base') {
baseElement = headChild;
}
}
const baseFragment = treeAdapter.createDocumentFragment();
if (!baseElement) {
baseElement = treeAdapter.createElement('base', undefined, [
{ name: 'href', value: this._options.baseHref },
]);
//coment the two lines below
// treeAdapter.appendChild(baseFragment, baseElement);
// indexSource.insert(headElement.__location.startTag.endOffset + 1, parse5.serialize(baseFragment, { treeAdapter }));
}
<script>
var items = document.location.href.split('/');
while (items.length>4)
items.pop();
document.write('<base href="' + items.join('/') + '" />');
</script>
app.UseMvc(routes =>
{
...
});
//Add this Middleware
app.Use(async (context, next) =>
{
string path = context.Request.Path.Value.Substring(1);
bool encontrado = path.EndsWith(".js") || path.EndsWith(".css") || path.EndsWith(".map") || path.StartsWith("sockjs");
if (!encontrado)
{
//make here the check for the pages
//"silly" e.g.
encontrado==(path=="es/adminitrator" || path=="it/administrator")
}
if (encontrado)
await next.Invoke();
else
{
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "error404.html"));
}
app.UseSpa(spa=>
{
....
}
});
import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}