WebSockets are not working in #microsoft/signalr - signalr

I Have configured the signalr with ASP NET core. When i use local service, it works properly. When i use after host it's not working as expected throws the below error.
Here is the code that i have done.
import * as signalR from '#microsoft/signalr';
const connection: signalR.HubConnection = new signalR.HubConnectionBuilder().withUrl('wss://demo/staging/web-services/hubs/spreadsheethub',
{
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
}).build();
...
});
connection.on('dataReceived', (data: string) => {
// code
});
connection.start().then(() => {
console.log('server connected!!!');
}).catch(err => console.log(err));

Related

.NET 7.0 and React Native not working with Axios call

My .NET api which was working perfectly well with .NET 6.x is not working with .NET 7. I can make http requests with Thunder Client and Swagger but it won't work with my React Native (expo) app. I tried it with Flutter as well and that didn't work. I get this error:
Possible Unhandled Promise Rejection (id: 1):
I'm using Axios to make the request. My appsettings.json looks like this:
...
"Kestrel": {
"Endpoints": {
"Http":{
"Url": "http://localhost:5000"
},
"Https":{
"Url": "https://localhost:5001"
}
}
},
...
My API call looks like this:
const baseUrl = 'https://localhost:5001/api/users';
const headers = {
"Content-Type": "application/json",
}
const [user, setUser] = useState(null);
useEffect(() => {
axios.get(baseUrl, {headers}).then((response) => {
setUser(response.data);
console.log(response.data);
}).catch(function(error){
console.log(error);
console.log(error.response.data);
});
}, []);
I have enabled CORS in by Program.cs
...
builder.Services.AddCors(options =>
{
options.AddPolicy(name: CorsPolicy,
policy =>
{
policy.WithOrigins
(
"exp://192.168.0.41:19000",
"http://localhost:19006",
"http://localhost:19000"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
...
app.UseCors(CorsPolicy);
...
Is this an issue with .NET 7.0 or is it just coincidence? How can I fix it?
react-native will not work with localhost calls use ngrok to handle this

Why does signalR stop pinging after 20minutes here?

I'm using signalr-no-jquery v0.1.10 to make a client - server connection. The problem is the client stops pinging after 20 minutes, I'm guessing it is some sort of default value in miliseconds. Where could I change this timeout to a higher value? The documentation is not exact or helpful in this version of signalR on how to do this. Maybe someone recognises where the config needs to be. I know the start() function can receive config but can it change the ping timeout for example? Again, the docs are scarce in this version of signalR. Currently my setup looks like this:
export const createSocketConnection = () => {
const URL = process.env.REACT_APP_API_URL;
return hubConnection(`${URL}/signalr`, { useDefaultPath: false })
};
export const createSocketProxy = (connection, hubName) => {
return connection.createHubProxy(hubName);
};
export const createSocketChannel = (eventName, proxy) =>
eventChannel((emit) => {
const messageHandler = (...data) => {
emit(data);
};
proxy.on(eventName, messageHandler);
return () => { };
});
export const startSocket = (socket) =>
new Promise((resolve) => {
socket.start().done(() => resolve());
});
export const stopSocket = (socket) =>
new Promise((resolve) => {
socket.stop().done(() => resolve());
});

Cannot connect to signalr hub from ionic app: Access to XMLHttpRequest ... has been blocked by CORS policy

I'm trying to develop a simple proof of concept for an ionic app sending and receiving signalr messages. I have a very simple signalr web app built in .net 4.5 that is succesfully sending and receiving messages from connected clients within the app host.
I am now trying to connect to this from an ionic app but I get the message
Access to XMLHttpRequest at 'http://localhost:59621/signalr/negotiate'
from origin 'http://localhost:8100' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: The
value of the 'Access-Control-Allow-Origin' header in the response must
not be the wildcard '*' when the request's credentials mode is
'include'.
when attempting to establish a connection to the signalr hub.
Any assistance is much appreciated.
.Net Code
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);
}
}
Ionic Code
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));
}
}
Ionic Info
Ionic:
ionic (Ionic CLI) : 4.0.6
Ionic Framework : ionic-angular 3.9.3
#ionic/app-scripts : 3.2.1
Cordova:
cordova (Cordova CLI) : 8.1.0
Cordova Platforms : none
System:
NodeJS : v8.11.0 (C:\Program Files\nodejs\node.exe)
npm : 5.6.0
OS : Windows 10
Environment:
ANDROID_HOME : not set
The problem was that the signalr plugin for ionic required a .Net Core backend. I had been attempting to use a .Net Framework backend.
Your code is fine. issue of CORS related. So You should run as below steps
Create shortcut chrome on desktop and rename no-cors (Whatever name)
Right click on icon and goes to property
Next change target to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:/Chrome" and save.
Then run on this breowser definitely it works. thanks

Azure signalr service context with Angular

Wondering if anyone has experience in the azure signalr service(v1.04) and angular cli(v6+). Having some issues understanding how to get the client context after connecting to the hub. Any thoughts?
Here's the context of the hub, any help would be appreciated!
this.getConnectionInfo().subscribe(info => {
console.log("INFO", info);
let options = {
accessTokenFactory: () => info.accessToken
};
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(info.hubUrl, options)
.configureLogging(signalR.LogLevel.Information)
.build();
this.hubConnection.start().then(() => {
console.log('Hub connection started init');
**[GET hubConnectionContext]**
console.log('Connection', this.hubConnection);
})
.catch(err => console.error(err.toString()));

Using Signalr on Angular 5 and Asp.net WebApi

I am actually creating a chat with angular 5 and signalR on an ASP.NET Framework API. I followed the documentation but it's still not work. Here is my hub:
public class ChatHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
}
Here is my startup class:
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
and here is my angular part which create the hubconnection:
ngOnInit() {
this._hubConnection = new HubConnection('http://localhost:58525/signalr/hubs');
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :( : ' + err));
this._hubConnection.on('send', data => {
console.log(data);
});
}
I get this error:
If your ASP.NET page runs on another server, then your URL looks not correct.
https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain
You have to connect to:
this._hubConnection = new HubConnection('http://localhost:58525/signalr');

Resources