Skip to content

Commit a4e43f2

Browse files
committed
change
1 parent a4385e3 commit a4e43f2

File tree

59 files changed

+3231
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+3231
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
3+
namespace SignalR.Controllers
4+
{
5+
[ApiController]
6+
[Route("[controller]")]
7+
public class WeatherForecastController : ControllerBase
8+
{
9+
private static readonly string[] Summaries = new[]
10+
{
11+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
12+
};
13+
14+
private readonly ILogger<WeatherForecastController> _logger;
15+
16+
public WeatherForecastController(ILogger<WeatherForecastController> logger)
17+
{
18+
_logger = logger;
19+
}
20+
21+
[HttpGet(Name = "GetWeatherForecast")]
22+
public IEnumerable<WeatherForecast> Get()
23+
{
24+
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
25+
{
26+
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
27+
TemperatureC = Random.Shared.Next(-20, 55),
28+
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
29+
})
30+
.ToArray();
31+
}
32+
}
33+
}

38.SignalR/SignalR/Hubs/ChatHub.cs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using Microsoft.AspNetCore.SignalR;
2+
using System.Collections.Generic;
3+
using System.Threading.Tasks;
4+
5+
6+
namespace SignalR.Hubs
7+
{
8+
9+
10+
public class ChatHub : Hub
11+
{
12+
private static Dictionary<string, string> ConnectedUsers = new();
13+
14+
public async Task SetUsername(string username)
15+
{
16+
if (!ConnectedUsers.ContainsKey(username))
17+
{
18+
ConnectedUsers[username] = Context.ConnectionId;
19+
await Clients.Caller.SendAsync("ReceivePrivateMessage", "System", $"You are connected as {username}");
20+
}
21+
else
22+
{
23+
await Clients.Caller.SendAsync("ReceivePrivateMessage", "System", "Username already in use.");
24+
}
25+
}
26+
27+
public override async Task OnDisconnectedAsync(Exception exception)
28+
{
29+
var user = ConnectedUsers.FirstOrDefault(u => u.Value == Context.ConnectionId);
30+
if (user.Key != null)
31+
{
32+
ConnectedUsers.Remove(user.Key);
33+
}
34+
await base.OnDisconnectedAsync(exception);
35+
}
36+
37+
// ✅ Private Message Handling
38+
public async Task SendPrivateMessage(string toUser, string message)
39+
{
40+
if (ConnectedUsers.TryGetValue(toUser, out string connectionId))
41+
{
42+
string fromUser = ConnectedUsers.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;
43+
await Clients.Client(connectionId).SendAsync("ReceivePrivateMessage", fromUser, message);
44+
}
45+
else
46+
{
47+
await Clients.Caller.SendAsync("ReceivePrivateMessage", "System", "User not found.");
48+
}
49+
}
50+
51+
// ✅ Group Chat Handling
52+
public async Task CreateGroup(string groupName)
53+
{
54+
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
55+
string user = ConnectedUsers.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;
56+
await Clients.Group(groupName).SendAsync("ReceiveGroupMessage", "System", $"{user} joined the group {groupName}");
57+
}
58+
59+
public async Task SendMessageToGroup(string groupName, string message)
60+
{
61+
string user = ConnectedUsers.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;
62+
await Clients.Group(groupName).SendAsync("ReceiveGroupMessage", user, message);
63+
}
64+
65+
public async Task LeaveGroup(string groupName)
66+
{
67+
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
68+
}
69+
}
70+
71+
72+
73+
}

38.SignalR/SignalR/Program.cs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using SignalR.Hubs;
2+
3+
var builder = WebApplication.CreateBuilder(args);
4+
5+
// Add services to the container.
6+
builder.Services.AddControllers();
7+
builder.Services.AddEndpointsApiExplorer();
8+
builder.Services.AddSwaggerGen();
9+
10+
// ✅ Add CORS to allow frontend clients
11+
builder.Services.AddCors(options =>
12+
{
13+
options.AddPolicy("CorsPolicy", builder =>
14+
{
15+
builder.WithOrigins("http://localhost:5500", "http://127.0.0.1:5500", "https://localhost:7141")
16+
.AllowAnyMethod()
17+
.AllowAnyHeader()
18+
.AllowCredentials();
19+
});
20+
});
21+
22+
23+
// ✅ Add SignalR Service
24+
builder.Services.AddSignalR();
25+
26+
var app = builder.Build();
27+
28+
// Configure the HTTP request pipeline.
29+
if (app.Environment.IsDevelopment())
30+
{
31+
app.UseSwagger();
32+
app.UseSwaggerUI();
33+
}
34+
35+
app.UseHttpsRedirection();
36+
37+
app.UseCors("CorsPolicy");
38+
39+
app.UseAuthorization();
40+
41+
app.MapControllers();
42+
43+
// ✅ Map SignalR Hub
44+
app.MapHub<ChatHub>("/chatHub");
45+
46+
app.Run();
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
{
2+
"$schema": "http://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:10197",
8+
"sslPort": 44357
9+
}
10+
},
11+
"profiles": {
12+
"http": {
13+
"commandName": "Project",
14+
"dotnetRunMessages": true,
15+
"launchBrowser": true,
16+
"launchUrl": "swagger",
17+
"applicationUrl": "http://localhost:5243",
18+
"environmentVariables": {
19+
"ASPNETCORE_ENVIRONMENT": "Development"
20+
}
21+
},
22+
"https": {
23+
"commandName": "Project",
24+
"dotnetRunMessages": true,
25+
"launchBrowser": true,
26+
"launchUrl": "swagger",
27+
"applicationUrl": "https://localhost:7141;http://localhost:5243",
28+
"environmentVariables": {
29+
"ASPNETCORE_ENVIRONMENT": "Development"
30+
}
31+
},
32+
"IIS Express": {
33+
"commandName": "IISExpress",
34+
"launchBrowser": true,
35+
"launchUrl": "swagger",
36+
"environmentVariables": {
37+
"ASPNETCORE_ENVIRONMENT": "Development"
38+
}
39+
}
40+
}
41+
}

38.SignalR/SignalR/SignalR.csproj

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net8.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.0" />
11+
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
12+
</ItemGroup>
13+
14+
</Project>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<ActiveDebugProfile>https</ActiveDebugProfile>
5+
</PropertyGroup>
6+
</Project>

38.SignalR/SignalR/SignalR.http

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@SignalR_HostAddress = http://localhost:5243
2+
3+
GET {{SignalR_HostAddress}}/weatherforecast/
4+
Accept: application/json
5+
6+
###

38.SignalR/SignalR/SignalR.sln

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.9.34723.18
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SignalR", "SignalR.csproj", "{0D4EDCCE-A208-464F-8862-B2930A9EF25B}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{0D4EDCCE-A208-464F-8862-B2930A9EF25B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{0D4EDCCE-A208-464F-8862-B2930A9EF25B}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{0D4EDCCE-A208-464F-8862-B2930A9EF25B}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{0D4EDCCE-A208-464F-8862-B2930A9EF25B}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {879CC960-5167-45EA-B7CF-35D049F395E8}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
namespace SignalR
2+
{
3+
public class WeatherForecast
4+
{
5+
public DateOnly Date { get; set; }
6+
7+
public int TemperatureC { get; set; }
8+
9+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
10+
11+
public string? Summary { get; set; }
12+
}
13+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}

0 commit comments

Comments
 (0)