【问题标题】:How to pass Custom Header from React JS client to SignalR hub?如何将自定义标头从 React JS 客户端传递到 SignalR 集线器?
【发布时间】:2019-01-22 04:21:38
【问题描述】:

我正在使用 Dot Net Core 2.0 设置一个新的 SignalR react 应用程序(“@aspnet/signalr”)。我想将自定义标头发送到 SignalR 集线器“协商”请求(例如 request.headers["MyHeader"] = "Header")。

我能够连接到集线器并获取数据以响应应用程序。我尝试通过覆盖传递给“withUrl”的选项中的 httpClient 来设置自定义标头。

使用此处提供的代码,我收到错误:“错误:无法完成与服务器的协商:错误:从协商未定义返回的意外状态代码”

当 httpClient 从选项中移除时,它会连接。

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

我将标头视为“Authorize”:“jwt token”的方式,我希望在“https://localhost:5001/chatHub/negotiate”请求中看到另一个标头为“MyHeader”:“NewHeader”

【问题讨论】:

  • 你能告诉我们console.log(JSON.stringify(httpOptions))post: (url, httpOptions) => { 之后记录的内容吗?注意:在发布之前查看打印的内容并清除所有机密数据
  • 或者只是console.log(JSON.stringify(httpOptions.headers)) ,但是您的 JS 看起来不错,所以我假设您的属性名称错误或其可能不可变
  • 它的“{content:””, headers:{Authorization: “jwt token”, MyHeader: “NewHeader}, method: “POST”, url: “localhost:5001/chatHub/negotiate”}”。这是整个 httpOptions
  • 我在 HttpConnection.js 中记录响应。上面的代码覆盖了“协商”请求的响应。所以“POST”中返回的任何东西都将是“协商”请求的响应。

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


【解决方案1】:

找到了答案。

httpClient.post 会覆盖默认 SignalR httpClient.post 的响应。

以下对 httpClient 的更新有效。

  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" 期望以这种形式得到响应。

{
    statusCode: 200,
    statusText: "ok",
    content: "<string response>"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多