You need to enable JavaScript to run this app. Angular(12) Universal SSR中如何传递子域名标识到.NET Core 3.1后端
优惠活动
大模型
产品
解决方案
定价
更多

Angular(12) Universal SSR中如何传递子域名标识到.NET Core 3.1后端

解决Angular Universal SSR中从子域名提取企业标识并传递到API请求头的问题

1. 在SSR入口(server.ts)中提取子域名

SSR渲染时,server.ts是处理客户端请求的入口,这里能直接拿到原始请求的host信息,比依赖Referer/Origin头更可靠。

// server.ts
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';

const app = express();

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModule,
}));

app.get('*', (req, res) => {
  // 解析host,提取子域名(适配companyidentifier.myapp.com格式)
  const host = req.headers.host || '';
  const subdomain = host.split('.')[0];
  // 将子域名注入Angular应用的依赖注入体系
  res.render('index', {
    req,
    res,
    providers: [
      { provide: 'COMPANY_IDENTIFIER', useValue: subdomain }
    ]
  });
});

2. 在Angular应用中共享子域名数据

使用TransferState确保服务器端提取的子域名能在SSR渲染和客户端激活时都可用:

// src/app/services/company-identifier.service.ts
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { TransferState, makeStateKey } from '@angular/platform-browser';

const COMPANY_ID_KEY = makeStateKey<string>('companyIdentifier');

@Injectable({ providedIn: 'root' })
export class CompanyIdentifierService {
  private _identifier: string;

  constructor(
    private transferState: TransferState,
    @Inject(PLATFORM_ID) private platformId: object,
    @Inject('COMPANY_IDENTIFIER') private serverIdentifier: string
  ) {
    if (isPlatformServer(this.platformId)) {
      // 服务器端直接使用注入的值,并存入TransferState
      this._identifier = serverIdentifier;
      this.transferState.set(COMPANY_ID_KEY, this._identifier);
    } else {
      // 客户端从TransferState读取服务器端传递的数据
      this._identifier = this.transferState.get(COMPANY_ID_KEY, '');
    }
  }

  get identifier(): string {
    return this._identifier;
  }
}

3. 用HttpInterceptor自动添加请求头

创建拦截器,在所有API请求中自动带上企业标识头:

// src/app/interceptors/api-header.interceptor.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { CompanyIdentifierService } from '../services/company-identifier.service';

@Injectable()
export class ApiHeaderInterceptor implements HttpInterceptor {

  constructor(private companyIdService: CompanyIdentifierService) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const companyId = this.companyIdService.identifier;
    if (companyId) {
      // 克隆请求并添加自定义请求头
      request = request.clone({
        setHeaders: {
          'X-Company-Identifier': companyId
        }
      });
    }
    return next.handle(request);
  }
}

在app.module.ts中注册拦截器:

// src/app/app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ApiHeaderInterceptor } from './interceptors/api-header.interceptor';

@NgModule({
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ApiHeaderInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

4. .NET Core后端配置

确保后端允许接收自定义请求头,若涉及跨域,在Startup.cs中配置CORS:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowCrmApi", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors("AllowCrmApi");
    // 其他中间件配置...
}

在API控制器中读取头信息:

[ApiController]
[Route("api/[controller]")]
public class CrmController : ControllerBase
{
    [HttpGet("data")]
    public IActionResult GetCrmData()
    {
        var companyId = Request.Headers["X-Company-Identifier"].FirstOrDefault();
        // 使用companyId处理业务逻辑
        return Ok(new { CompanyId = companyId });
    }
}

内容的提问来源于stack exchange,提问作者irfan HASBEK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 00:48:19