1

我正在尝试学习如何使用Azure functionSignalR创建无服务器设计。为此,我创建了以下类Azure function

    public static class NotifactionR
    {

        [FunctionName("negotiate")]
        public static SignalRConnectionInfo Negotiate(
            [HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req,
            [SignalRConnectionInfo(HubName = "my-hub")]
            SignalRConnectionInfo connectionInfo)
        {
            // connectionInfo contains an access key token with a name identifier claim set to the authenticated user
            return connectionInfo;
        }

        [FunctionName("NotifactionR")]
        public static Task NotifactionR([EventGridTrigger]EventGridEvent eventGridEvent,
            [SignalR(HubName = "my-hub")]IAsyncCollector<SignalRMessage> signalRMessages,
            ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());

            return signalRMessages.AddAsync(
                new SignalRMessage
                {
                    // the message will only be sent to these user IDs
                    UserId = "userId1",
                    Target = "OnNewEvent",
                    Arguments = new[] { eventGridEvent.Data }
                });
        }
    }

我在我的设备上使用了以下配置local.settings.json来启用本地测试:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureSignalRConnectionString": "Endpoint=https://myservice.service.signalr.net;AccessKey=myaccess-token;Version=1.0;",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  },
  "Host": {
    "CORS": "http://localhost:7071",
    "CORSCredentials": true
  }
}

为了测试这一点,刚刚创建了一个HTML file包含以下脚本的内容:

const connection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:7071/api", { headers: { 'Access-Control-Allow-Origin': 'http://localhost:7071'}})
      .configureLogging(signalR.LogLevel.Trace)
      .build();

connection.on('OnNewEvent', ProcessMyEvent);
connection.onclose(() => console.log('disconnected'));
console.log('connecting...');

connection.start()
    .then(() => data.ready = true)
    .catch(console.error);

当我在 Chrome 上打开 HTML 文件时,我看到以下错误(问题在 Firefox 中也几乎相同):

connecting...
Utils.ts:189 [2019-07-27T16:13:01.573Z] Debug: Starting HubConnection.
Utils.ts:189 [2019-07-27T16:13:01.573Z] Debug: Starting connection with transfer format 'Text'.
Utils.ts:189 [2019-07-27T16:13:01.575Z] Debug: Sending negotiation request: http://localhost:7071/api/negotiate.

SignalRTest.html:1 Access to XMLHttpRequest at 'http://localhost:7071/api/negotiate' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Utils.ts:182 [2019-07-27T16:13:02.147Z] Warning: Error from HTTP request. 0: .
Utils.ts:179 [2019-07-27T16:13:02.148Z] Error: Failed to complete negotiation with the server: Error
Utils.ts:179 [2019-07-27T16:13:02.148Z] Error: Failed to start the connection: Error
Error
    at new HttpError (Errors.ts:20)
    at XMLHttpRequest.xhr.onerror (XhrHttpClient.ts:76)

有人对我在这里做错了什么有任何想法吗?

更新 1

这是我test.html正在使用的文件

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://unpkg.com/@aspnet/signalr@1.1.4/dist/browser/signalr.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
    <script>
        window.apiBaseUrl = 'http://localhost:7071';

        function initialize() {
            const connection = new signalR.HubConnectionBuilder()
                .withUrl(window.apiBaseUrl + "/api", { headers: { 'Access-Control-Allow-Origin': 'http://localhost:7071' } })
                .configureLogging(signalR.LogLevel.Trace)
                .build();

            connection.on('OnNewEvent', ProcessMyEvent);
            connection.onclose(() => console.log('disconnected'));
            console.log('connecting...');

            connection.start({ withCredentials: false })
                .then(() => console.log('ready...'))
                .catch(console.error);

        }
        function ProcessMyEvent(vehicle) {
            alert("ProcessMyEvent CALLED");
        }

        initialize();


    </script>
</head>
<body>

</body>

</html>

更新 2:

我还尝试使用以下命令从命令提示符运行它:

c:\Users\Kiran\AppData\Local\AzureFunctionsTools\Releases\2.26.0\cli\func host start --cors * --pause-on-error

我仍然得到同样的错误

4

1 回答 1

4

这有点像红鲱鱼,似乎与我的 CORS 无关。我看到您正在使用 Azure SignalR 服务,您连接到该服务的方式与标准 SignalR 不同。

negotiate函数的行为与 SignalR 服务不同。 negotiate将返回一些数据以及 accessToken 和 SignalR 服务的 URL,您需要使用此 URL 来连接。

我在下面添加了一个示例,说明它应该如何工作。(我没有对此进行测试,但希望你能明白)。

function initialize() {
    axios.get(window.apiBaseUrl+"/api/negotiate").then(response => {        
        const options = {
            accessTokenFactory: () => response.data.accessToken
        }
        const socket = new SignalR.HubConnectionBuilder()
            .withUrl(response.data.url, options)
            .build(SignalR.HttpTransportType.None)

        connection.on('OnNewEvent', ProcessMyEvent);
        connection.onclose(() => console.log('disconnected'));
        console.log('connecting...');

        connection.start({ withCredentials: false })
            .then(() => console.log('ready...'))
            .catch(console.error);
    });
}
于 2019-07-30T08:02:46.127 回答