我正在尝试学习如何使用Azure function
和SignalR
来创建无服务器设计。 为此,我为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:UsersKiranAppDataLocalAzureFunctionsToolsReleases2.26.0clifunc host start --cors * --pause-on-error
我仍然得到同样的错误
这有点像红鲱鱼,似乎与我无关。我看到你使用的是 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);
});
}