【发布时间】:2019-08-05 13:00:34
【问题描述】:
我正在尝试为发送和接收信号器消息的离子应用程序开发一个简单的概念证明。我有一个内置于 .net 4.5 的非常简单的 Signalr Web 应用程序,它可以成功地从应用程序主机中连接的客户端发送和接收消息。
我现在正在尝试从 ionic 应用程序连接到此,但我收到了消息
在“http://localhost:59621/signalr/negotiate”访问 XMLHttpRequest 来自原点“http://localhost:8100”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查: 响应中“Access-Control-Allow-Origin”标头的值必须 当请求的凭据模式为时,不是通配符“*” '包括'。
尝试建立与信号器集线器的连接时。
非常感谢任何帮助。
.Net 代码
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
};
map.RunSignalR(hubConfiguration);
});
}
}
ChatHub.cs
[HubName("ChatHub")]
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
}
离子密码
import { Component } from '@angular/core';
import { NavController, DateTime, AlertController } from 'ionic-angular';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
hubConnection: HubConnection;
name: string;
message: string;
messages: string[] = [];
constructor(public navCtrl: NavController, public alertCtrl: AlertController) {
}
ionViewDidLoad() {
}
ionViewWillEnter() {
let alert = this.alertCtrl.create({
title: 'Demo',
message: 'What is your name?',
inputs: [
{
name: 'Name',
placeholder: 'Name'
}
],
buttons: [
{
text: 'Enter',
handler: data => {
this.name = data.Name;
}
}
]
});
alert.present();
this.hubConnection = new HubConnectionBuilder().withUrl('http://localhost:59621/signalr').build();
this.hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => {
debugger;
console.log('Error while establishing connection :(')
});
this.hubConnection.on('addNewMessageToPage', (name: string, receivedMessage: string) => {
const text = `${name}: ${receivedMessage}`;
this.messages.push(text);
});
}
sendMessage() {
this.hubConnection
.invoke('send', this.name, this.message)
.then(() => this.message = '')
.catch(err => console.error(err));
}
}
离子信息
离子:
离子(离子 CLI):4.0.6
离子框架:离子角 3.9.3
@ionic/app-scripts : 3.2.1
科尔多瓦:
科尔多瓦(科尔多瓦 CLI):8.1.0 Cordova 平台:无
系统:
NodeJS : v8.11.0 (C:\Program Files\nodejs\node.exe) npm:5.6.0 操作系统:Windows 10
环境:
ANDROID_HOME:未设置
【问题讨论】:
标签: asp.net ionic-framework cors signalr ionic4