将标头添加到@ aspnet / signalr Javascript客户端

时间:2019-02-22 11:06:23

标签: signalr signalr-hub signalr.client asp.net-core-signalr

我正在使用This npm package上的@ aspnet / signalr官方Javascript客户端

我想知道是否可以将Header配置添加到客户端连接头中

我如何建立连接

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

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

图书馆说

     *
 * @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;}

答案 2 :(得分:0)

进行一些研究后更新

似乎signalR js / ts客户端库不支持以任何方式添加自定义标头

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

由于地址栏中未显示信号R URL连接,因此它有点安全

例如

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

答案 3 :(得分:0)

基本上,您可以为hubConnecitonBuilder提供一个自定义HttpClient,它允许您对signalR请求做任何您想做的事情,这对我来说是天蓝色的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();

在我的情况下,我的自定义标头(在此处不可见)由我的有角度的应用程序HTTP拦截器添加,该拦截器现在可以拦截@ aspnet / signalr http请求并添加适当的标头,因为我使用我的应用程序HttpClient发出我的请求图书馆之一。

相关问题