添加headers到@aspnet/signalrJavascript客户端

Add headers to @aspnet/signalr Javascript client

我正在使用来自This npm package

的@aspnet/signalr官方Javascript客户端

想知道有没有办法在客户端连接上添加Header配置header

我如何建立连接

let connection = new signalR.HubConnectionBuilder() .withUrl( "https://some.signalr-host.com" ) .build();

研究后更新

似乎 signalR js/ts 客户端库无论如何都不支持添加自定义 headers

因此,我们的解决方案是通过查询字符串发送参数,并让服务器 API 支持它

由于信号R URL连接没有显示在地址栏中,所以有点安全

例如

const connection = new HubConnectionBuilder()
      .withUrl(
        `${signalrUrl}&${key}=${value}`)
      .build();

基本上,您可以向 hubConnecitonBuilder 提供自定义 HttpClient,它允许您对 signalR 请求做任何您想做的事情,这对于我来说是 azure APIManagement 背后的协商部分非常有趣:

 let options: IHttpConnectionOptions = {
      httpClient: <HttpClientSignalR>{
        getCookieString: (url) => {
          return '';
        },
        post: (url, httpOptions) => {
          return this.http.post(url, null, {
            headers: httpOptions.headers,
            withCredentials: false
          })
            .toPromise()
            .then(
              res => {
                return {
                  statusCode: 200,
                  statusText: null,
                  content: JSON.stringify(res)
                };
              },
              err => err
            );
        }
      }
    }

    this._hubConnection = new HubConnectionBuilder()
      .withUrl(environment.host_url + this.routes.notification + '?userId=' + userId, options)
      .build();

在我的例子中,我的自定义 headers(此处不可见)由我的 angular 应用程序 http 拦截器添加,现在可以拦截 @aspnet/signalr http 请求并添加适当的 headers,因为我正在使用我的应用程序 HttpClient 发出我的请求而不是库请求。

图书馆说

     *
 * @param {string} url The URL the connection will use.
 * @param {IHttpConnectionOptions} options An options object used to configure the connection.
 * @returns The {@link signalr.HubConnectionBuilder} instance, for chaining.
 */
withUrl(url: string, options: IHttpConnectionOptions): HubConnectionBuilder;

以及我们在代码中实现时的样子:

const connection = new signalR.HubConnectionBuilder()
.withUrl(url, {
  accessTokenFactory: () => {
    return getAccessToken();
  },
})
.withAutomaticReconnect()
.build();


async function getAccessToken() {
const scopes = {
  scopes: authenticationParameters.extraScopesToConsent,
};
const tokenObject = await authProvider.getAccessToken(scopes);
return tokenObject.accessToken;}

2020年初IHttpConnectionOptionsgot a headers property的定义。(在文档网站上看不到,但在Typescript定义文件中。)您现在可以执行以下操作:

const connection = new signalR.HubConnectionBuilder()
  .withUrl("https://some.signalr-host.com", {
       headers: {"foo": "bar"}
   })
  .build();