asp.net - 无法从 ionic 应用程序连接到信号器集线器:访问 XMLHttpRequest ... 已被 CORS 策略阻止
问题描述
我正在尝试为发送和接收信号器消息的离子应用程序开发一个简单的概念证明。我有一个非常简单的 Signalr Web 应用程序,内置于 .net 4.5 中,它可以成功地从应用程序主机中连接的客户端发送和接收消息。
我现在正试图从一个离子应用程序连接到这个,但我收到了消息
从源“ http://localhost:8100 ”访问“ http://localhost:59621/signalr/negotiate ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:值当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头不能是通配符“*”。
尝试建立与信号器集线器的连接时。
非常感谢任何帮助。
.Net 代码
启动.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);
});
}
}
聊天中心.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科尔多瓦平台:无
系统:
NodeJS:v8.11.0 (C:\Program Files\nodejs\node.exe) npm:5.6.0 操作系统:Windows 10
环境:
ANDROID_HOME:未设置
解决方案
问题在于 ionic 的信号器插件需要一个 .Net Core 后端。我一直在尝试使用 .Net Framework 后端。
推荐阅读
- jquery - 键入新标签时 Select2 失去焦点
- reactjs - 如何为 react 和 django 应用程序编写 bitbucket-pipelines.yml 以部署在 heroku 上
- python - Python 字符串到文件
- python - 如何在 Discord.py 中按 ID 踢用户
- python - scapy 嗅探 ZigBee 流量,不检测 ZigBee 层
- vba - 从模板创建后如何使新文档可见?
- java - 如何修改我的信用卡验证程序以仅在我最后一个检查卡类型的函数中检查有效数字?
- sql - SQL 语法错误:“缺少右括号”
- ruby - 如何防止硒无头中的虚假用户代理检测?
- javascript - 如何获取层次结构中所有节点的路径