zinab_elgendy 5 months ago
parent
commit
55fece9d44

+ 34 - 0
MTWorkHR.API/Chat/ChatHub.cs

@@ -0,0 +1,34 @@
+using Microsoft.AspNetCore.SignalR;
+
+namespace MTWorkHR.API.Chat
+{
+    public sealed class ChatHub : Hub<IChatClient>
+    {
+
+        public override async Task OnConnectedAsync()
+        {
+            await Clients.All.ReceiveMessage($"{Context.ConnectionId} has joined");
+        }
+        public async Task SendMessage(string message)
+        {
+            await Clients.All.ReceiveMessage($"{Context.ConnectionId} :{message}");
+        }
+
+
+        public async Task askServer(string someTextFromClient)
+        {
+            string tempString;
+
+            if (someTextFromClient == "hey")
+            {
+                tempString = "message was 'hey'";
+            }
+            else
+            {
+                tempString = "message was something else";
+            }
+
+            await Clients.Client(this.Context.ConnectionId).ReceiveMessage(tempString);
+        }
+    }
+}

+ 7 - 0
MTWorkHR.API/Chat/IChatClient.cs

@@ -0,0 +1,7 @@
+namespace MTWorkHR.API.Chat
+{
+    public interface IChatClient
+    {
+        Task ReceiveMessage(string message);
+    }
+}

+ 1 - 0
MTWorkHR.API/MTWorkHR.API.csproj

@@ -10,6 +10,7 @@
   </PropertyGroup>
 
   <ItemGroup>
+    <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.8" />
     <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.1">
       <PrivateAssets>all</PrivateAssets>
       <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

+ 14 - 1
MTWorkHR.API/Program.cs

@@ -14,6 +14,8 @@ using Microsoft.OpenApi.Models;
 using MTWorkHR.API.Swagger;
 using Azure.Storage.Blobs;
 using Microsoft.Extensions.DependencyInjection;
+using MTWorkHR.API.Chat;
+using Microsoft.AspNetCore.SignalR;
 
 var builder = WebApplication.CreateBuilder(args);
 var config = new AppSettingsConfiguration();
@@ -97,7 +99,10 @@ builder.Services.AddSwaggerGen(swagger =>
                     }
                 });
 });
-
+builder.Services.AddSignalR(options =>
+{
+    options.EnableDetailedErrors = true;
+});
 //--------------------------
 var app = builder.Build();
 
@@ -115,10 +120,18 @@ app.UseCors(x => x
     .SetIsOriginAllowed(origin => 
     true) // allow any origin
     .AllowCredentials()); // allow credentials
+
+
+app.MapPost("broadcast", async (string message, IHubContext<ChatHub, IChatClient> context) =>
+{
+    await context.Clients.All.ReceiveMessage(message);
+    return Results.NoContent();
+});
 app.UseHttpsRedirection();
 app.UseAuthentication();
 app.UseAuthorization();
 app.UseMiddleware<LoggingMiddleware>();
 app.MapControllers();
+app.MapHub<ChatHub>("chat-hub");
 
 app.Run();