[英]Server side rendering. Web API and Angular 2
我開發了一個使用ASP.NET Core Web API
和Angular 4
構建的Web應用程序。 我的模塊捆綁Web Pack 2
是Web Pack 2
。
我想通過Facebook,Twitter,Google使我的應用程序可抓取或鏈接共享。 當某些用戶試圖在Facebook上發布我的新聞時,該url
必須相同。 例如,Jon希望在Facebook上與網址共享頁面 - http://myappl.com/#/hellopage
,然后Jon將此鏈接插入Facebook: http://myappl.com/#/hellopage
: http://myappl.com/#/hellopage
。
我已經看過這個沒有標簽幫助器的Angular Universal服務器端渲染教程,並希望進行服務器端渲染。 由於我使用ASP.NET Core Web API
並且我的Angular 4
應用程序沒有任何.cshtml
視圖,所以我無法從控制器發送數據通過我的控制器通過ViewData["SpaHtml"]
查看:
ViewData["SpaHtml"] = prerenderResult.Html;
另外,我看到了Angular Universal的這個谷歌教程 ,但他們使用的是NodeJS
服務器,而不是ASP.NET Core
。
我想使用服務器端預呈現。 我通過這種方式添加元標記:
import { Meta } from '@angular/platform-browser';
constructor(
private metaService: Meta) {
}
let newText = "Foo data. This is test data!:)";
//metatags to publish this page at social nets
this.metaService.addTags([
// Open Graph data
{ property: 'og:title', content: newText },
{ property: 'og:description', content: newText }, {
{ property: "og:url", content: window.location.href },
{ property: 'og:image', content: "http://www.freeimageslive.co.uk/files
/images004/Italy_Venice_Canal_Grande.jpg" }]);
當我在瀏覽器中檢查此元素時,它看起來像這樣:
<head>
<meta property="og:title" content="Foo data. This is test data!:)">
<meta property="og:description" content="Foo data. This is test data!:)">
<meta name="og:url" content="http://foourl.com">
<meta property="og:image" content="http://www.freeimageslive.co.uk/files
/images004/Italy_Venice_Canal_Grande.jpg"">
</head>
我通常的方式引導應用程序:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
我的webpack.config.js
配置如下所示:
var path = require('path');
var webpack = require('webpack');
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var WebpackNotifierPlugin = require('webpack-notifier');
var isProd = (process.env.NODE_ENV === 'production');
function getPlugins() {
var plugins = [];
// Always expose NODE_ENV to webpack, you can now use `process.env.NODE_ENV`
// inside your code for any environment checks; UglifyJS will automatically
// drop any unreachable code.
plugins.push(new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
}));
plugins.push(new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}));
plugins.push(new CleanWebpackPlugin(
[
'./wwwroot/js',
'./wwwroot/fonts',
'./wwwroot/assets'
]
));
return plugins;
}
module.exports = {
devtool: 'source-map',
entry: {
app: './persons-app/main.ts' //
},
output: {
path: "./wwwroot/",
filename: 'js/[name]-[hash:8].bundle.js',
publicPath: "/"
},
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html']
},
devServer: {
historyApiFallback: true,
stats: 'minimal',
outputPath: path.join(__dirname, 'wwwroot/')
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules/,
loader: 'tslint-loader',
enforce: 'pre'
},
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular2-template-loader',
'angular-router-loader',
'source-map-loader'
]
},
{
test: /\.js/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
},
{
test: /\.(png|jpg|gif|ico)$/,
exclude: /node_modules/,
loader: "file?name=img/[name].[ext]"
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ['to-string-loader', 'style-loader', 'css-loader'],
},
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ["style", "css", "sass"]
},
{
test: /\.html$/,
loader: 'raw'
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
loader: 'file?name=fonts/[name].[ext]'
}
],
exprContextCritical: false
},
plugins: getPlugins()
};
是否可以在沒有ViewData
情況下ViewData
服務器端渲染? 是否有另一種方法可以在ASP.NET Core Web API和Angular 2中進行服務器端渲染?
我已經將一個示例上傳到github存儲庫 。
Angular中有一個選項可以使用HTML5樣式的URL(沒有哈希): LocationStrategy和瀏覽器URL樣式 。 您應該選擇此URL樣式。 對於要與Facebook共享的每個URL,您需要呈現整個頁面,如您引用的教程中所示。 在服務器上擁有完整的URL,您可以呈現相應的視圖並返回HTML。
由@DávidMolnár提供的代碼可能非常適用於此目的,但我還沒有嘗試過。
更新:
首先,要使服務器預useHash: true
工作,您不應該使用useHash: true
來阻止將路由信息發送到服務器。
在您引用的GitHub問題中提到的演示ASP.NET Core + Angular 2通用應用程序中,ASP.NET Core MVC Controller和View僅用於以更方便的方式從Angular服務器預呈現的HTML。 對於應用程序的其余部分,只有WebAPI用於.NET Core世界,其他一切都是Angular和相關的Web技術。
使用Razor視圖很方便,但如果你嚴格反對它,你可以直接將HTML硬編碼到控制器動作中:
[Produces("text/html")]
public async Task<string> Index()
{
var nodeServices = Request.HttpContext.RequestServices.GetRequiredService<INodeServices>();
var hostEnv = Request.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>();
var applicationBasePath = hostEnv.ContentRootPath;
var requestFeature = Request.HttpContext.Features.Get<IHttpRequestFeature>();
var unencodedPathAndQuery = requestFeature.RawTarget;
var unencodedAbsoluteUrl = $"{Request.Scheme}://{Request.Host}{unencodedPathAndQuery}";
TransferData transferData = new TransferData();
transferData.request = AbstractHttpContextRequestInfo(Request);
transferData.thisCameFromDotNET = "Hi Angular it's asp.net :)";
var prerenderResult = await Prerenderer.RenderToString(
"/",
nodeServices,
new JavaScriptModuleExport(applicationBasePath + "/Client/dist/main-server"),
unencodedAbsoluteUrl,
unencodedPathAndQuery,
transferData,
30000,
Request.PathBase.ToString()
);
string html = prerenderResult.Html; // our <app> from Angular
var title = prerenderResult.Globals["title"]; // set our <title> from Angular
var styles = prerenderResult.Globals["styles"]; // put styles in the correct place
var meta = prerenderResult.Globals["meta"]; // set our <meta> SEO tags
var links = prerenderResult.Globals["links"]; // set our <link rel="canonical"> etc SEO tags
return $@"<!DOCTYPE html>
<html>
<head>
<base href=""/"" />
<title>{title}</title>
<meta charset=""utf-8"" />
<meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
{meta}
{links}
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/css/flag-icon.min.css"" />
{styles}
</head>
<body>
{html}
<!-- remove if you're not going to use SignalR -->
<script src=""https://code.jquery.com/jquery-2.2.4.min.js""
integrity=""sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=""
crossorigin=""anonymous""></script>
<script src=""http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.0.min.js""></script>
<script src=""/dist/main-browser.js""></script>
</body>
</html>";
}
請注意,后備URL用於處理HomeController
中的所有路由並呈現相應的角度路徑:
builder.UseMvc(routes =>
{
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
為了更容易開始考慮采用該演示項目並對其進行修改以適合您的應用程序。
更新2:
如果你不需要像使用NodeServices的Razor那樣使用ASP.NET MVC中的任何東西,那么在Node.js服務器上使用服務器預渲染來托管Universal Angular應用程序會更自然。 並獨立托管ASP.NET Web Api,以便Angular UI可以訪問不同服務器上的API。 我認為從API獨立托管靜態文件(並在案例中使用服務器預渲染)是非常常見的方法。
這是在Node.js上托管的Universal Angular的首發回購: https : //github.com/angular/universal-starter 。
以下是如何在不同服務器上托管UI和Web API的示例: https : //github.com/thinktecture/nodejs-aspnetcore-webapi 。 請注意如何在urlService.ts
配置API URL。
此外,您可以考慮隱藏反向代理后面的UI和API服務器,以便可以通過相同的公共域和主機訪問它們,並且您不必處理CORS以使其在瀏覽器中工作。
根據您的鏈接教程,您可以直接從控制器返回HTML。
預呈現頁面將在http://<host>
:
[Route("")]
public class PrerenderController : Controller
{
[HttpGet]
[Produces("text/html")]
public async Task<string> Get()
{
var requestFeature = Request.HttpContext.Features.Get<IHttpRequestFeature>();
var unencodedPathAndQuery = requestFeature.RawTarget;
var unencodedAbsoluteUrl = $"{Request.Scheme}://{Request.Host}{unencodedPathAndQuery}";
var prerenderResult = await Prerenderer.RenderToString(
hostEnv.ContentRootPath,
nodeServices,
new JavaScriptModuleExport("ClientApp/dist/main-server"),
unencodedAbsoluteUrl,
unencodedPathAndQuery,
/* custom data parameter */ null,
/* timeout milliseconds */ 15 * 1000,
Request.PathBase.ToString()
);
return @"<html>..." + prerenderResult.Html + @"</html>";
}
}
請注意Produces
屬性,該屬性允許返回HTML內容。 看到這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.