0

I am setting up a new SignalR react app ("@aspnet/signalr") with Dot Net Core 2.0. I want to send custom headers to SignalR hub "negotiate" request (like request.headers["MyHeader"] = "Header").

I am able to connect to hub and get data back to react app. I have tried setting custom header by trying to overwrite httpClient in options passed to "withUrl".

With the code provided here I am getting error: "Error: Failed to complete negotiation with the server: Error: Unexpected status code returned from negotiate undefined"

It connects when httpClient is removed from options.

import { HubConnectionBuilder } from '@aspnet/signalr';


const options = {
  accessTokenFactory: () => {
    return "jwt token";
  },
  httpClient: {
    post: (url, httpOptions) => {

      httpOptions.headers = {
        ...httpOptions.headers,
        MyHeader: "NewHeader"
      };
      httpOptions.method = "POST";
      httpOptions.url = url;

      return httpOptions;
    }
  }
};

const connection = new HubConnectionBuilder()
   .withUrl("https://localhost:5001/chatHub", options)
   .build();

connection.start().catch(function(err) {
   console.log("Error on Start : ", err);
});

The way I see header as "Authorize": "jwt token", I expect to see another header in "https://localhost:5001/chatHub/negotiate" request as "MyHeader": "NewHeader"

Kolz
  • 11
  • 1
  • 2
  • Can you show us what `console.log(JSON.stringify(httpOptions))` logs right after `post: (url, httpOptions) => {`. NOTE: **Review what that prints out prior to posting and scrub any confidential data** – cantuket Jan 22 '19 at 04:40
  • Or just `console.log(JSON.stringify(httpOptions.headers)) `, but your JS looks fine so I'm presuming you have the wrong property name or its potentially immutable – cantuket Jan 22 '19 at 04:42
  • Its “{content:””, headers:{Authorization: “jwt token”, MyHeader: “NewHeader}, method: “POST”, url: “https://localhost:5001/chatHub/negotiate”}”. This is entire httpOptions – Kolz Jan 22 '19 at 12:37
  • I was logging response in HttpConnection.js. Above code overwrites response of “negotiate” request. So anything returned in “POST” will be the response of “negotiate” request. – Kolz Jan 22 '19 at 13:20

1 Answers1

1

Found answer to this.

httpClient.post overwrites the response of default SignalR httpClient.post.

Below update to httpClient worked.

  httpClient: {
    post: (url, httpOptions) => {
      const headers = {
        ...httpOptions.headers,
        MyHeader: "MyHeader"
      };

      return axios.post(url, {}, { headers }).then(response => {
        return (newResponse = {
          statusCode: response.status,
          statusText: response.statusText,
          content: JSON.stringify(response.data)
        });
      });
    }
  }

SignalR "negotiate" expects response in this form.

{
    statusCode: 200,
    statusText: "ok",
    content: "<string response>"
}
Kolz
  • 11
  • 1
  • 2