How to invoke a SignalR Core hub method from Postman WebSocket - signalr

I have a SignalR Core 5.0 app that works in Visual Studio 2019. I will deploy the SignalR server to IIS but want to do some testing in Postman using the new WebSockets.
Taking one of my hub methods in my VS project, let's call it "SomeHubMethod" that returns some data, what is the proper syntax to invoke the hub method?
For instance, how would I translate this C# invoke for Postman WebSocket?
SomeHubMethod = The hub method
groupxyz = The name of the client originating the call to SignalR server, and so the response from the server should be sent to "groupxyz". Let's say the response is "Hello World!"
"1234" = Just some test data.
In my VS project...
private async void SendSomeHubMethod()
{
await connection.InvokeAsync("SomeHubMethod", "groupxyz", "1234");
}
Where the response would be received in my class...
connection.On<string>("TheHubResponse", (m) =>
{
_ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Debug.WriteLine(m));
// Hello World!
});
My assembled request that I found in link below for Postman WebSocket...
{"arguments":["groupxyz", "1234"],"invocationId":"0","target":"SomeHubMethod","type":1}
On Send, Postman shows Connected but "Hello World!" is not returned from my hub.
I found this post but it is not detailed on invoke.
reference example

You can but it's kinda problematic, so let's start from beginning..
When you have your defined SignalR hub endpoint (ie. wss://localhost:5005/hub/notifications) then
Make a POST request to following URL (notice the https, not the wss): https://localhost:5005/hub/notifications/negotiate?negotiateVersion=1.
In answer you will receive following information:
{
"negotiateVersion": 1,
"connectionId": "zJ1cqyAe4FRyLCGMzzC0Fw",
"connectionToken": "HYunLu0j0IHdBY4NNrkm0g",
"availableTransports": [
{
"transport": "WebSockets",
"transferFormats": [
"Text",
"Binary"
]
},
{
"transport": "ServerSentEvents",
"transferFormats": [
"Text"
]
},
{
"transport": "LongPolling",
"transferFormats": [
"Text",
"Binary"
]
}
]
}
Get the connectionToken from the step above and copy it. Now open a websocket connection with your hub like following:
wss://localhost:5005/hub/notifications?id={connectionToken} where connectionToken is the token from previous step. The url should look like: wss://localhost:5005/hub/notifications?id=HYunLu0j0IHdBY4NNrkm0g.
Now hold something.. according to the Microsoft documentation (https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/HubProtocol.md#overview) we need to send a handshake request with following informations:
{
"protocol": "json",
"version": 1
}
It's hard to achieve by plain text because it needs to ends with a 0xE1 ASCII character, so we need to convert the handshake request with that character to base64 and send it. I did it for you and this string is:
eyJwcm90b2NvbCI6Impzb24iLCAidmVyc2lvbiI6MX0e
Now when we have all these info, let's deep dive into Postman:
Connect to the endpoint:
Just send a request with string I pasted above to this URL with content-type: Binary using Base64.
As you can see, we are receiving message {"type": 6} what means we are connected to the Hub and it's pinging us.
You can now send/receive any messages from your hub:
Now you can change the content-type to JSON and invoke your hub endpoints.

How to invoke a SignalR Core hub method from Postman WebSocket
Short answer, you can't.
Long answer, SignalR is a protocol that requires certain ceremony to start sending and receiving messages. For example, you need an ID in the query string that is generated by the server. Then you need to send the handshake request over the transport before you can start making invocations.

Related

Is there a way to modify the request body during PACT verification?

I am trying to run a PACT test on the provider side and I don't know how to manipulate the request body that I get from the Pact file. I need to do this because I have to use an id from State step.
In my case, I need to perform a request in State step and afterwards to use the response of that request in the actual Pact verification test. So, I would like to replace a value from the pact file with the one obtained in the State.
Also, for being even more complicated, my body is an XML. So here it is how my pact request looks like:
"request": {
"method": "POST",
"path": "/path/url",
"headers": {
"Content-Type": "application/xml"
},
"body": "<note> <to>John</to> <from>Jane</from> <subject>Reminder</subject> </note>"
}
As I said, in the Provider State I will have a request and the response of this will be let's say 'Mary'. So my question would be how can I replace 'Jane' with 'Mary' in the Pact request body when executing the verification test? Thanks.
I have managed to solve my problem, modifying the request in TargetRequestFilter.
#TargetRequestFilter
public void updateRequest(HttpPost request) {
HttpEntity entity = request.getEntity();
String body = EntityUtils.toString(entity);
body = replace(body, "Jane", "Mary");
entity = new StringEntity(body);
request.setEntity(entity);
}
This piece of code will modify the request right before making the call and will send the desired value instead the one that we have in the Pact file.

http post request to api nativescript vue

Hello I need help with http post request to my server and get response with authentication.
Look on the screens on 1 I use insomnia REST API application. Using this app I got success response with premium days and id.
In second image I got response just from my nativescript vue.js app where I got false response.
There is something wrong with my code. please tell me what.
You are sending a JSON object in your request body from {N} app, on the other hand you are using FormData with your REST client for testing.
You must either change your API to support JSON data on request body which is generally the standard way. In case if you can't do that, then you must use the nativescript-background-http plugin to send FormData. It will be something like,
var params = [
{ name: "username", value: "test" },
{ name: "password", value: "test123" },
{ name: "uuid", value: "xxxx" }
];
var task = session.multipartUpload(params, request);

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.

FCM with Postman - The request was missing an Authentication Key (FCM Token)

//body its like this
{
"to":
"/topics/NEWS"
,
"data":{
"extra_information": "This is some extra information"
},
//notification that i need to give
"notification":{
"title": "ChitChat Group",
"text": "You may have new messages",
"click_action":"ChatActivity"
}
}
The 401 error pertains that your Authorization Key is invalid or incorrect.
When using Postman, add a key= prefix for the value of Authorization, like so:
key=AAA...
See below for a tutorial on Sending Downstream FCM Messages using Postman.
Also, for your notification message payload, text isn't one of the valid parameters, I think you were looking for message instead.
Sending Downstream Messages using Postman
To do this in Postman, you simply have to set the following:
Set request type to POST
In the Headers, set the following:
Content-Type = application/json
Authorization = < Your FCM Server Key > (See your Firebase Console's Cloud Messaging Tab)
Set the payload parameters in the Body (*in this example, we used the raw option, see screenshot (2)*)
Send the request to https://fcm.googleapis.com/fcm/send
Screenshots:
(1)
Note: Always keep your Server Key a secret. Only a portion of my key is visible here so it should be fine.
(2)
(3)
Notice that the request was a success with the message_id in the response.
Wrong:
Authorization:AIzaSyDDk77PRpvfhh......
Correct:
Authorization:key=AIzaSyDDk77PRpvfhh......
Full example:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
While the answers above are still correct, you may choose to use HTTP v1. This requires Bearer instead of key= and uses an Oauth2 access token instead of a server key string. To view HTTP v1 specifications, please refer to the link below:
https://firebase.google.com/docs/cloud-messaging/migrate-v1
I was also getting same error in PHP , solved with below header :
$header = array("authorization: key=" . $this->apiKey . "","content-type: application/json");

How can I use notification actions with Firebase Messaging Web SDK

How do I use notification actions with the Firebase Messaging SDK on the web?
There are a few common pitfalls people hit when attempting this.
Firebase Notifications - There is a feature of the Firebase Messaging SD
K's none as "Firebase Notifications". When you send a push message to a Firebase Instance-ID (IID) token, you can use a "notification" key which the SDK's will look for and if found, construct a notification for you. The benefit of this is that you have to write no code to show a notification. The downside is that it can be restrictive if you want to do anything complex or perform work on the device once the notification is received. So to use actions, you MUST NOT USE THIS. Instead call the FCM API with the IID token and a "data" payload.
Data Payload - The data payload has a restriction where it can only be key value pairs, where the value must be a string, i.e. no arrays. What this means is that you can't just send an array of actions and construct a notification with that. The way around this is to create a JSON string, send that to the FCM API and then parse and use the JSON on the device.
Time for an example.
Calling the FCM API
The format of your payload should be something like this:
{
"data": {
"some-data": "Im a string",
"some-other-data": "Im also a string",
"json-data": "{\"actions\": [{\"action\":\"yes\", \"title\":\"Yes\"},{\"action\":\"no\",\"title\":\"No\"}]}"
},
"to": "YOUR-IID-TOKEN"
}
You can send this with curl like so:
curl -X POST -H "Authorization: key=YOUR-SERVER-KEY" -H "Content-Type: application/json" -d '{
"data": {
"some-data": "Im a string",
"some-other-data": "Im also a string",
"json-data": "{\"actions\": [{\"action\":\"yes\", \"title\":\"Yes\"},{\"action\":\"no\",\"title\":\"No\"}]}"
},
"to": "YOUR-IID-TOKEN"
}' "https://fcm.googleapis.com/fcm/send"
With that you'll be able to get the data in the onBackgroundMessage callback in your service worker.
Receiving the Payload on the Device
In a service worker we could have the following code:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Message received: ', payload);
});
Which would print out the following in the console:
Notice the JSON data is still just a string, not an object.
Next up we can parse the JSON data and check its the right format to use as our notification actions.
We can change our code to the following:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Message received: ', payload);
const parsedJSON = JSON.parse(payload.data['json-data']);
console.log('Actions:', parsedJSON);
});
This will give the following log:
With this, we can finally create our notification with the following code:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Message received: ', payload);
const parsedJSON = JSON.parse(payload.data['json-data']);
console.log('Actions:', parsedJSON);
// Customize notification here
const notificationTitle = 'Actions Title';
const notificationOptions = {
body: 'Actions body.',
actions: parsedJSON.actions,
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
Now you should have a notification with actions:
Testing
As Meggin as pointed out in the comments, it's not obvious how to test it, so a few guiding principles.
The biggest pain point is that if your web server sets a cache header for you service worker file, it won't update between refreshes, one way to fix this it to open your service worker file in a new tab and refresh that page until your service worker is up to date (This is viewing the actual source code of your service worker). Then when you refresh your web page your service worker will be the latest one and you can tell it's updated by the number next to the service worker incrementing.
Alternatively, just unregister the service worker the service worker and refresh the page - this should give you the latest service worker.
To test your notification, you'll need to click a tab that is for a different web page before sending a push message.
The reason for this is that if the user is currently on one of your pages, the push message is sent to the pages onMessage() callback instead of the onBackgroundMessage() callback.
Following Matt's advice, I was able to get a proper notification with content from my firebase function passed into my service worker (including actions), but I had to pass all of my data through the one json object, otherwise it wouldn't work for me.
Here's what my firebase functions code looks like:
function sendPayload(tokenArray) {
const payload = {
"data": {
"jsondata": "{\"body\":\"Meggin needs help\", \"title\":\"Can you help her make the code work?\",\"actions\": [{\"action\":\"yes\", \"title\":\"Yes\"},{\"action\":\"no\",\"title\":\"No\"}]}"
}
};
admin.messaging().sendToDevice(tokenArray, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
}
And here's what my code looks like in my service worker:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Payload received: ', payload);
const parsedJSON = JSON.parse(payload.data.jsondata);
console.log("What does actions look like? " + parsedJSON.actions);
console.log("What does title look like? " + parsedJSON.title);
const notificationTitle = parsedJSON.title;
const parsedBody = parsedJSON.body;
const parsedActions = parsedJSON.actions;
// Customize notification here
const notificationOptions = {
body: parsedBody,
actions: parsedActions,
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
It's worth noting that one major hurdle that helped me get passed this is understanding how to test push notifications and service workers!
You actually can't see my notification unless the browser is closed, so obviously, you can't watch the console.
But then once you've pushed the notification, you go into the console, and change the file at the top of console to be the service worker file specifically.
And then you can see the console logs!
I realize this might seem obvious to many people, but it wasn't to me, and it's crucial to understanding how to parse the payload and get it to do what you want!

Resources