将信号器与 vue/vuex 连接

Connect signalr with vue / vuex

我正在尝试将 SignalR 集线器连接到 Vue 组件,但我没有这样做。我用谷歌搜索 "vue with signalr" 并且几乎每个 link 都是真实的,直到第二页。 我得到了一个 cors 来源,但我不认为这是主要问题,因为我对网络 api 的 post/get 调用运行良好。 c# 端口号 63213,客户端在 8080

我也在使用 vuex,我想知道我是否应该在商店连接。 这里是代码示例。我使用 vue/vuex 和 typescript falvor。

  mounted: function() {
    //... under mounted, signalR connection.  i am using import * as signalR from "@aspnet/signalr";  
  this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:63213/ChatHub")
      .build();

    // connecting to the hub
    this.hubConnection
      .start()
      .then(() => console.log("connection started"))
      .catch(err => console.log("connecting hub failed err is : ", err));

    //at the hub there is a function named broadcastMessage, should return string that will be added to an array. should it be at sotr's getter  
    this.connection.on("broadcastMessage", function(msg: string) {
      this.messages.push({ msg });
    });
  },

c#

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var policy = new CorsPolicy()
            {
                AllowAnyOrigin = true,
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                SupportsCredentials = true
            };

            policy.Origins.Add("http://localhost:8080");

            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }

中心

public class ChatHub : Hub
    {

        public static void SendMessage(string msg)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            hubContext.Clients.All.broadcastMessage(msg, " !! !! ");
        }
    }

错误是:

对“http://localhost:63213/ChatHub/negotiate' from origin 'http://localhost:8080”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有 'Access-Control-Allow-Origin' header 存在于请求的资源。

我应该将集线器连接传递给商店吗? 我做错了什么?

谢谢。

切换到 .core 对象。

在"Configure"

之下
app.UseCors(builder => builder.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader().AllowCredentials());

app.UseSignalR(route => {route.MapHub<UserHub>("/user-hub");} );

下 配置服务

services.AddSignalR();
services.AddCors();

在 vue 组件 (ts)

created: function() {
    this.$userHub.$on("user-added-event", this.userAddedEvent);
  },
  beforeDestroy: function() {
    //clean SignalR event
    this.$userHub.$off("user-added-event", this.userAddedEvent);
  },

user-hub.js 用于处理连接。 作为 vue 插件导入

import { HubConnectionBuilder, LogLevel } from "@aspnet/signalr";
export default {
  install(Vue) {

    const connection = new HubConnectionBuilder()
      .withUrl(`${Vue.prototype.$http.defaults.baseURL}/user-hub`) 
      .configureLogging(LogLevel.Information)
      .build();


    const userHub = new Vue();

    Vue.prototype.$userHub = userHub;

    connection.on("AddUserEvent", (userId, userName) => {
      userHub.$emit("user-added-event", { userId, userName });
    });

    // if connection closed, reopen it
    let startedPromise = null;
    function start() {
      startedPromise = connection.start().catch(err => {
        return new Promise((resolve, reject) =>
          setTimeout(
            () =>
              start()
                .then(resolve)
                .catch(reject),
            5000
          )
        );
      });
      return startedPromise;
    }

    connection.onclose(() => start());

    start();
  }
};

完整项目将上传至 git。