Blazor Application /_blazor/disconnect statuscode 400 - nginx

my blazor app seems to work but im trying to understand why I'm getting a 400error as seen in the screenshot.
Who can give me a HINT for what Blazor needs technically the "disconnect" ?
SCREENSHOT-disconnect
I'm running everything on a NGINX webserver.
thx Fabio

That call happens here in the code on the window unload event and is used to tell the signalr server that you are disconnecting.
If you are seeing a lot of these it may be that your proxy is not configured correctly for websocket connections.
window.addEventListener(
'unload',
() => {
const data = new FormData();
const circuitId = circuit.circuitId!;
data.append('circuitId', circuitId);
navigator.sendBeacon('_blazor/disconnect', data);
},
false
);

There's a bug reported for this issue here:
https://github.com/dotnet/aspnetcore/issues/30316
Blazor.server.js not respecting configureSignalR builder defined
url/path for disconnnects
As a work-around, I added this to Startup.cs in the Configure method:
var rewriteOptions = new RewriteOptions();
rewriteOptions.AddRewrite("_blazor/disconnect", "/_blazor/disconnect", skipRemainingRules: true);
app.UseRewriter(rewriteOptions);

Related

Koa SSE connection reconnecting

I have set up an SSE connection using Koa like so:
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
// Sets up the HTTP header and sends a message via SSE
function writeSSE(ctx, message) {
ctx.res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*',
});
ctx.res.write(`id: 01\n`);
ctx.res.write(`data: ${message}\n\n`);
}
// Router Middleware
router.get('/stream', (ctx, next) => {
writeSSE(ctx, 'Stream reached.');
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8080);
Where my React components starts the connection like so:
new EventSource("http://localhost:8080/stream")
The component then receives the answer sent by the writeSSE method on the backend.
But for some reason the /stream endpoint is reached every 3 seconds or so, as if the connection was being reestablished.
And my error listener on the front-end catches a CONNECTING event every time.
this.state.source.onerror = (e) => {
if (e.target.readyState == EventSource.CONNECTING) {
console.log("Connecting...");
}
};
And on the back-end, ctx.response equals { status: 404, message: 'Not Found', header: {} }.
Would anyone know the cause of this issue? Is it linked to the way I use Koa?
this is a bit too late, but I will write my experience with sse using Koa.
First of all using ctx.res directly is not much appreciated by Koa, if you still want to use it make sure to put ctx.respond = false to bypass koa response mecanism.
In my experience a stream is the best way to use SSE with Koa you can do something like :
const stream = require('stream');
const koa = require('koa');
const app = new koa();
app.use(async ctx => {
ctx.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
ctx.status = 200;
const stream = new stream.PassThrough()
ctx.body = stream; // here koa will pipe the ctx.res to stream and end the ctx.res when ever the stream ends.
let counter = 5;
const t = setInterval(() => {
stream.write(`data: hi from koa sse ${counter}`);
counter--;
if (counter === 0) {
stream.end();
clearInterval(t);
}
}, 1000);
});
Hope this help anyone will play with SSE on koa.
PS: I wrote this on hurry if there is anything wrong with code tell me and I will correct it.
I'm in the process of implementing a Koa-based server for SSE. I've been running into the same problem, and here are my thoughts / working solution:
As far as I can tell, the reason why onmessage and onerror keep getting called is because the EventSource object on the client side is emitting an error event. This is causing the connection to be disconnected, which causes the client to send another request to initialize the stream to the server. From here, the process repeats itself indefinitely.
Based on my own testing, EventSource is emitting an error due to the data that is being sent back from the server. Per the docs, a 200 response that has as Content-Type other than 'text/event-stream' will cause a failure.
In your example, you have declared your response as 'text/event-stream' and are passing a string into the ctx.res.write method. While this looks correct, and in fact works when using comparable code and Express, it seems that it doesn't work in Koa. However, if you change the 'data' you are writing to your response to a stream, such as this example here, you'll find that the connection establishes correctly.
Maybe try the following:
//require Passthrough
const PassThrough = require('stream').PassThrough;
//then, in your writeSSE function, try this:
let stream = new PassThrough();
stream.write(`data: ${message}\n\n`);
ctx.res.write(stream);
I'm not 100% sure why this change works. My best guess is that there is something about Koa's ctx object that prevents a plain string or template literal from being viewed as valid text/event-stream data, but this is entirely supposition (this begs the question as to why it works in Express, but hopefully someone more knowledgeable can answer this for both of us). From what I've seen of other snippets published online, the stream approach is the one to take in Koa.
I'm not sure what your results will be, as it looks like you may be using a different version of Koa than I am, but I'd give it a shot. I was able to get my connection established correctly making this small change.

Unknown http error with http request to an iis server with ionic

I've got a problem with my ionic app. I try to get a json object from my iis (asp.NET) server. But the request doesn't even come into my controller. Everytime, i get the same error:
http failure response for (unknown url) 0 unknown error
At first, I thought it was just a cors problem so i fixed it but now, it works with chrome and internet explorer 11 but not with edge and, more important, it doesn't work on device.
I don't think the problem is with my typescript code since there is no problem with a Google request... But, just in case, there is my code:
this.http.get('http://localhost:60196', {withCredentials : true}).subscribe(data => {
this.testData = JSON.stringify(data);
}, err => {
this.testData = JSON.stringify(err);
});
For the record: my iis server use windows impersonation and my app must run on windows devices (i didn't try my code with android or ios devices).
Thank you very much.
it doesn't work on device
this.http.get('http://localhost:60196', {withCredentials : true}).subscribe(data => {
this.testData = JSON.stringify(data);
}, err => {
this.testData = JSON.stringify(err);
});
Get request is rerencing to localhost. Here should be some Api endpoint when testing it on device...

SignalR: getting error: WebSocket closed

I am working on project of Ionic with angular and AspNet with SignalR that have chat module.
I use SignalR for Chat.It's working smoothly but some time i am getting error as per below screen shot and because of that it's get stop working at all.
I have hosted my service on IIS and creating proxy and communicating with client and server. Here is sample
(function () {
angular
.module('app')
.factory('SignalRFactory', SignalRFactory);
SignalRFactory.$inject = ['$rootScope', 'Hub', 'ionicToast'];
function SignalRFactory($rootScope, Hub, ionicToast) {
var signalRLocal = this;
var serverURL = 'https://serivcerURL.com/signalr';
//Hub setup
var hub = new Hub('CommunicationHub', {
rootPath: serverURL,
listeners: {
'send': function (data) {
console.log("send " + data);
}
},
errorHandler: function (error) {
//Here i am getting that websocket closed error
console.error(error);
}
});
signalRLocal.Connect = function (user) {
console.log("SignalR Connecting as :" + user.UserName);
hub.invoke('connect', user);
};
return signalRLocal;
}
})();
I have hosted service on IIS. I search for the solution and find something like this link
I also try with above link solution by using "long Polling" as per below
Hub.connection.start({ transport: 'longPolling' });
But i don't want to use "long Polling" at all.
So can someone help me to figure out this issue without use of 'long Polling'.
Can someone tell me what configuration i have to do at client side or at IIS level.
As we said in comments, SignalR client will try to reconnect after the connection is lost. Besides, many factors (such as physical network interruption, client browser failure, server offline etc) can cause the connection lost, this article explains some disconnection scenarios, you can refer to it and find the possible causes of the issue.
Besides, as I mentioned in comment, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients) to start a new connection to make client automatically re-establish a connection after it has been lost.
edit:
The connection to ws://localhost:3156/signalr/signalr/connect?transport=webSoc‌​kets&clientProtocol=‌​1.5&connectionToken=‌​g8vpRv9ncVDjPIYB9UuE‌​pAAILEaOcTMTG9p46IA2‌​4 was interrupted while the page was loading.
Under "Client disconnection scenarios" section in the article, you can find:
In a browser client, the SignalR client code that maintains a SignalR connection runs in the JavaScript context of a web page. That's why the SignalR connection has to end when you navigate from one page to another, and that's why you have multiple connections with multiple connection IDs if you connect from multiple browser windows or tabs. When the user closes a browser window or tab, or navigates to a new page or refreshes the page, the SignalR connection immediately ends because SignalR client code handles that browser event for you and calls the Stop method.
I am trying same and my client is in vue.js. I have changed below in vue.config.js
module.exports = {
devServer: {
proxy: {
'/hub': {
target: 'https://localhost:5001',
changeOrigin: false,
secure: false,
headers: {
'x-forwarded-proto': 'http',
},
},
},
},
}
Previously i am trying 'x-forwarded-proto': 'https', when I changed to http its work.
https://localhost:5001 is my .net endpoint and http://localhost:8080 is my vue enpoint
Changed in Startup.csbelow,
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<CardsHub>("/hub/cardsHub");
});
Added below code in vue component
this.connection = new signalR.HubConnectionBuilder()
.withUrl('/hub/cardsHub')
.build()
In my case the culprit was the wrong version of Microsoft.AspNetCore.SignalR.Common
the default one installed was 5.0.3
but I was targeting 3.1.0
Downgrading to 3.1.12 fixed the issue with the connection.

Angular2 CORS issue

I'm new to angular2 and to be fair I have very few knowledges which I try to fix, however I've run into some issues about cross site request, trying to access a service from another application but I have this issue whatever I try to do
XMLHttpRequest cannot load https://hr/Team/EditEmployeeInfo.aspx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54396' is therefore not allowed access. The response had HTTP status code 401.
This is my angular2 service and I've tried something like this
getUserHrtbProfile(userId): Promise<any> {
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET, PUT, POST, DELET');
headers.append('Access-Control-Allow-Origin', '*');
var apiUri: string = "https://hrtb/Team/EditEmployeeInfo.aspx?emplid={0}&Menu=InfoEmployee&T=0".replace("{0}", userId);
return this.http.get(apiUri, headers).map(result => result.json()).toPromise();
}
and this is my component
this.bannerService.getUserHrtbProfile(this.userId).then(hrtbJson => {
this.hasHrtbAccess = hrtbJson.HasHrtbAccess;
this.hrtbProfileUrl = hrtbJson.HrtbProfileUrl;
}).catch(err => {
this.hasHrtbAccess = false;
});
I've search a solution on my problem but still could not find one that suits my need.
Angular 2 http request with Access-Control-Allow-Origin set to *
But most important, is this an angular2 problem that I need to solve? Or in fact as I've read it should have been handled by the team that exposes the API?
Thank you all.
You need to enable CORS on your API backend.
Only for testing purpose you could use this Chrome Extension to simulate CORS on your api backend:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
You are trying to make request on other domain, this is what you can not resolve here. try with making request at you backed code, this will resolve you issue.

Connect two Meteor applications using DDP

I have two applications that I need to synchronise. One of them will receive data from users and the other will display the data. Both applications will work on different servers. They could be disconnected at some times and they need to continue working until reconnect, so I will replicate the data from the first application on the second application.
On Meteor documentation I found DDP.connect(url)but I'm not sure how to use it. I found many questions and examples connecting non Meteor applications with Meteor using DDP, but nothing about connecting two Meteor applications.
My first approach was something like this:
Application 1
Items = new Meteor.Collection('items');
Items.insert({name: 'item 1'});
if (Meteor.isServer) {
Meteor.publish('items', function() {
return Items.find();
});
}
Application 2
Items = new Meteor.Collection('items')
if (Meteor.isServer) {
var remote = DDP.connect('http://server1.com/);
remote.onReconnect = function() {
remote.subscribe('items');
var items = Items.find();
console.log(items.count()); // expected to be 1 but get 0
}
}
On the second application, how can I get the items from the first application?
I got a clue from this question How to properly use Meteor.connect() to connect with another Meteor server. I missed it because it was about the old Meteor.connect() that changed to DDP.connect().
This worked on client and server
var remote = DDP.connect('http://server1.com/');
Items = new Meteor.Collection('items', remote);
remote.subscribe('items', function() {
var items = Items.find();
console.log(items.count()); // get 1
});
Now I can watch for changes in application 1 from application 2 using Items.find().observe()
Warning
There is a bug on Meteor that will stop the connection between applications:
https://github.com/meteor/meteor/issues/1543
DDP between two servers doesn't reconnect
Update
The bug was solved
Update 2
This is a sample project tested with Meteor 0.6.6.2 https://github.com/camilosw/ddp-servers-test

Resources