Add headers to @aspnet/signalr Javascript client

天大地大妈咪最大 提交于 2021-01-27 21:02:46

问题


I'm using @aspnet/signalr Official Javascript client from This npm package

I wondering if there is the way to add Header configuration to the client connection header

How I build the connection

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


回答1:


Update after doing some research

Seems like signalR js/ts client library doesn't support adding customize headers in anyways

So, our solution is sending parameters through query string instead and made the server API to support it

Since signal R URL connection is not shown in the address bar, so it a bit secure

e.g.

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



回答2:


Basically you can provide a custom HttpClient to the hubConnecitonBuilder which allows you do whatever you want with the signalR requests, it can be very interesting for the negotiation part which was behind an azure APIManagement for me:

 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();

In my case, my custom headers (invisible here) are added by my angular app http interceptors which can now intercept the @aspnet/signalr http requests and add proper headers, as I m using my app HttpClient to emit my request instead of the library one.



来源:https://stackoverflow.com/questions/54825739/add-headers-to-aspnet-signalr-javascript-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!