You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
2. Then add `app.UseStaticFiles();` before `app.UseRouting();`in`Startup.cs` to support static files. Remove the default `endpoints.MapGet` inside `app.UseEndpoints`.
@@ -90,7 +90,6 @@ First let's create an empty ASP.NET Core app.
90
90
}
91
91
92
92
app.UseStaticFiles();
93
-
94
93
app.UseRouting();
95
94
96
95
app.UseEndpoints(endpoints =>
@@ -114,25 +113,44 @@ You can test the server by running `dotnet run --urls http://localhost:8080` and
114
113
115
114
You may remember in the [publish and subscribe message tutorial](./tutorial-pub-sub-messages.md) the subscriber uses an API in Web PubSub SDK to generate an access token from connection string and use it to connect to the service. This is usually not safe in a real world application as connection string has high privilege to do any operation to the service so you don't want to share it with any client. Let's change this access token generation process to a REST API at server side, so client can call this API to request an access token every time it needs to connect, without need to hold the connection string.
116
115
117
-
1. Install dependencies
118
-
Install dependencies and use [Secret Manager](/aspnet/core/security/app-secrets#secret-manager) tool for .NET Core to set the connection string. Run the below command, replacing `<connection_string>` with the one fetched in [previous step](#get-the-connectionstring-for-future-use)
116
+
1. Install dependencies.
119
117
120
118
```bash
121
119
dotnet add package Microsoft.Extensions.Azure
122
120
```
123
121
124
-
2. DI the service client inside `ConfigureServices` and don't forget to replace `<connection_string>` with the one of your services.
122
+
2. Add a `SampleChatHub` class to handle hub events. And DI the service middleware and service client inside `ConfigureServices()`. Don't forget to replace `<connection_string>` with the one of your services.
125
123
126
124
```csharp
127
125
public void ConfigureServices(IServiceCollection services)
128
126
{
129
-
services.AddAzureClients(builder =>
127
+
services.AddWebPubSub(o => o.ServiceEndpoint = new ServiceEndpoint("<connection_string>"))
128
+
.AddWebPubSubServiceClient<SampleChatHub>();
129
+
}
130
+
131
+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2. Add a `/negotiate` API to the server inside `app.UseEndpoints` to generate the token
150
+
151
+
`AddWebPubSubServiceClient<THub>()` is used to inject the service client `WebPubSubServiceClient<THub>`, with which we can use in negotiation step to generate client connection token and in hub methods to invoke service REST APIs when hub events are triggered.
152
+
153
+
3. Add a `/negotiate` API to the server inside `app.UseEndpoints` to generate the token.
136
154
137
155
```csharp
138
156
app.UseEndpoints(endpoints =>
@@ -146,7 +164,7 @@ You may remember in the [publish and subscribe message tutorial](./tutorial-pub-
146
164
await context.Response.WriteAsync("missing user id");
147
165
return;
148
166
}
149
-
var serviceClient = context.RequestServices.GetRequiredService<Azure.Messaging.WebPubSub.WebPubSubServiceClient>();
167
+
var serviceClient = context.RequestServices.GetRequiredService<WebPubSubServiceClient<SampleChatHub>>();
@@ -156,7 +174,7 @@ You may remember in the [publish and subscribe message tutorial](./tutorial-pub-
156
174
157
175
You can test this API by running `dotnet run --urls http://localhost:8080` and accessing `http://localhost:8080/negotiate?id=<user-id>` and it will give you the full url of the Azure Web PubSub with an access token.
158
176
159
-
3. Then update `index.html` to include the following script to get the token from server and connect to service
177
+
4. Then update `index.html` to include the following script to get the token from server and connect to service.
160
178
161
179
```html
162
180
<html>
@@ -176,8 +194,7 @@ You may remember in the [publish and subscribe message tutorial](./tutorial-pub-
176
194
</html>
177
195
```
178
196
179
-
If you are using Chrome, you can test it by opening the home page, input your user name. press F12 to open the Developer Tools window, switch to **Console** table and you'll see `connected` being printed in browser console.
180
-
197
+
If you are using Chrome, you can test it by opening the home page, input your user name. Press F12 to open the Developer Tools window, switch to **Console** table and you'll see `connected` being printed in browser console.
181
198
182
199
# [JavaScript](#tab/javascript)
183
200
@@ -285,7 +302,7 @@ You may remember in the [publish and subscribe message tutorial](./tutorial-pub-
285
302
</html>
286
303
```
287
304
288
-
If you are using Chrome, you can test it by opening the home page, input your user name. press F12 to open the Developer Tools window, switch to **Console** table and you'll see `connected` being printed in browser console.
305
+
If you are using Chrome, you can test it by opening the home page, input your user name. Press F12 to open the Developer Tools window, switch to **Console** table and you'll see `connected` being printed in browser console.
289
306
290
307
# [Java](#tab/java)
291
308
@@ -459,7 +476,7 @@ You may remember in the [publish and subscribe message tutorial](./tutorial-pub-
459
476
</html>
460
477
```
461
478
462
-
If you are using Chrome, you can test it by opening the home page, input your user name. press F12 to open the Developer Tools window, switch to **Console** table and you'll see `connected` being printed in browser console.
479
+
If you are using Chrome, you can test it by opening the home page, input your user name. Press F12 to open the Developer Tools window, switch to **Console** table and you'll see `connected` being printed in browser console.
463
480
464
481
---
465
482
@@ -472,63 +489,35 @@ Events are delivered to server in the form of Webhook. Webhook is served and exp
472
489
Azure Web PubSub follows [CloudEvents](./reference-cloud-events.md) to describe the event data.
473
490
474
491
# [C#](#tab/csharp)
475
-
For now, you need to implement the event handler by your own in C#, the steps are straight forward following [the protocol spec](./reference-cloud-events.md) and illustrated below.
492
+
Here we're using Web PubSub middleware SDK, there is already an implementation to parse and process CloudEvents schema, so we don't need to deal with these details. Instead, we can focus on the inner business logic in the hub methods.
476
493
477
494
1. Add event handlers inside `UseEndpoints`. Specify the endpoint path for the events, let's say `/eventhandler`.
478
-
479
-
2. First we'd like to handle the abuse protection OPTIONS requests, we check if the header contains `WebHook-Request-Origin` header, and we return the header `WebHook-Allowed-Origin`. For simplicity for demo purpose, we return`*` to allow all the origins.
3. Then we'd like to check if the incoming requests are the events we expect. Let's say we now care about the system `connected` event, which should contain the header `ce-type` as `azure.webpubsub.sys.connected`. We add the logic after abuse protection:
502
+
2. Go the `SampleChatHub` we created in previous step. Add a constructor to work with `WebPubSubServiceClient<SampleChatHub>` so we can use to invoke service. And override `OnConnectedAsync()` method to respond when `connected` event is triggered.
In the above code, we simply print a message to console when a client is connected. You can see we use `context.Request.Headers["ce-userId"]` so we can see the identity of the connected client.
520
+
In the above code, we use the service client to broadcast a notification message to all of whom is joined.
532
521
533
522
# [JavaScript](#tab/javascript)
534
523
@@ -629,50 +618,35 @@ Besides system events like `connected` or `disconnected`, client can also send m
629
618
630
619
# [C#](#tab/csharp)
631
620
632
-
The `ce-type` of `message` event is always `azure.webpubsub.user.message`, details see [Event message](./reference-cloud-events.md#message).
621
+
Implement the `OnMessageReceivedAsync()` method in `SampleChatHub`.
This event handler uses `WebPubSubServiceClient.SendToAllAsync()` to broadcast the received message to all clients.
649
+
This event handler uses `WebPubSubServiceClient.SendToAllAsync()` to broadcast the received message to all clients. You can see in the end we returned `UserEventResponse`, which contains a message directly to the caller and make the WebHook request success. If you have extra logic to validate and would like to break this call, you can throw an exception here. The middleware will deliver the exception message to service and service will drop current client connection.
676
650
677
651
2. Update `index.html` to add the logic to send message from user to server and display received messages in the page.
678
652
@@ -713,41 +687,6 @@ The `ce-type` of `message` event is always `azure.webpubsub.user.message`, detai
713
687
714
688
You can see in the above code we use `WebSocket.send()` to send message and `WebSocket.onmessage` to listen to message from service.
715
689
716
-
3. Finally update the `onConnected` handler to broadcast the connected event to all clients so they can see who joined the chat room.
717
-
718
-
```csharp
719
-
app.UseEndpoints(endpoints =>
720
-
{
721
-
var serviceClient = context.RequestServices.GetRequiredService<Azure.Messaging.WebPubSub.WebPubSubServiceClient>();
Now run the server using `dotnet run --urls http://localhost:8080` and open multiple browser instances to access http://localhost:8080/index.html, then you can chat with each other.
752
691
753
692
The complete code sample of this tutorial can be found [here][code-csharp].
0 commit comments