Skip to content

Commit 59ddda6

Browse files
committed
Adds more confs for handlers and try to fix error with swagger when using attribute
1 parent 54779bb commit 59ddda6

8 files changed

Lines changed: 68 additions & 28 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
3+
namespace Examples.Controllers;
4+
5+
[ApiController]
6+
[Route("/api/v1/test")]
7+
public class TestDefaultController : ControllerBase
8+
{
9+
10+
[HttpGet]
11+
public async Task<IActionResult> TestController([FromBody] string TextTest)
12+
{
13+
return Ok("Test");
14+
}
15+
}

Examples/Program.cs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System.Net.WebSockets;
22
using yawaflua.WebSockets;
33
using yawaflua.WebSockets.Core;
4-
using yawaflua.WebSockets.Models.Interfaces;
54

65
namespace Examples;
76

@@ -22,18 +21,20 @@ await Host.CreateDefaultBuilder(args)
2221

2322
internal class Startup
2423
{
25-
public void ConfigureServices(IServiceCollection services)
24+
public static void ConfigureServices(IServiceCollection services)
2625
{
2726
services.SettingUpWebSockets();
2827
services.AddRouting();
28+
services.AddControllers();
29+
services.AddEndpointsApiExplorer();
2930
services.AddHttpLogging();
3031
services.AddSingleton<TestWebSocketServer>();
3132
services.AddSingleton<ChatController>();
3233
services.AddSingleton(new WebSocketConfig()
3334
{
34-
OnOpenHandler = async (socket, context) =>
35+
OnOpenHandler = async (socket, _) =>
3536
{
36-
if (socket.WebSocketManager!.GetAllClients().Count(k =>
37+
if (socket.WebSocketManager.GetAllClients().Count(k =>
3738
Equals(k.ConnectionInfo!.RemoteIpAddress!.MapToIPv4(),
3839
socket.Client.ConnectionInfo!.RemoteIpAddress!.MapToIPv4())) >= 3)
3940
{
@@ -42,15 +43,16 @@ public void ConfigureServices(IServiceCollection services)
4243
Console.WriteLine($"{socket.Client.Id} has been connected to {socket.Client.Path}");
4344
}
4445
});
45-
services.AddScoped<IConfiguration>(k => new ConfigurationBuilder()
46+
services.AddScoped<IConfiguration>(_ => new ConfigurationBuilder()
4647
.AddJsonFile("appsettings.json", true)
4748
.Build());
4849
}
4950

50-
public void Configure(IApplicationBuilder app)
51+
public static void Configure(IApplicationBuilder app)
5152
{
52-
app.ConnectWebSockets();
5353
app.UseRouting();
54+
55+
app.UseWebSocketWithSwagger();
5456
app.UseHttpLogging();
5557
app.UseWelcomePage();
5658

yawaflua.WebSockets/Attributes/WebSocketAttribute.cs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using JetBrains.Annotations;
22
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.AspNetCore.Mvc.ApiExplorer;
4+
using Microsoft.AspNetCore.Mvc.Routing;
35

46
namespace yawaflua.WebSockets.Attributes;
57

@@ -18,13 +20,17 @@ namespace yawaflua.WebSockets.Attributes;
1820
/// When applied to methods, defines specific sub-routes (requires class-level base path).
1921
/// </remarks>
2022
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
21-
public class WebSocketAttribute : RouteAttribute
23+
[ApiExplorerSettings(IgnoreApi = true)]
24+
public class WebSocketAttribute : RouteAttribute, IRouteTemplateProvider, IApiDescriptionVisibilityProvider
2225
{
2326
/// <summary>
2427
/// Original route template specified in attribute
2528
/// </summary>
26-
public string Template { get; }
27-
29+
public new string Template { get; }
30+
31+
public new int? Order { get; } = 0;
32+
public new string? Name { get; }
33+
2834
/// <summary>
2935
/// Creates WebSocket route definition
3036
/// </summary>
@@ -36,5 +42,8 @@ public class WebSocketAttribute : RouteAttribute
3642
public WebSocketAttribute([RouteTemplate]string path) : base(path)
3743
{
3844
Template = path;
45+
Name = path;
3946
}
47+
48+
public bool IgnoreApi => true;
4049
}

yawaflua.WebSockets/Core/WebSocketConfig.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,7 @@ namespace yawaflua.WebSockets.Core;
66
public class WebSocketConfig
77
{
88
public Func<IWebSocket, HttpContext, Task>? OnOpenHandler { get; set; } = null;
9+
public Func<Exception, IWebSocket, HttpContext, Task>? OnErrorHandler { get; set; } = null;
10+
public Func<Exception, HttpContext, Task>? OnConnectionErrorHandler { get; set; } = null;
911

1012
}

yawaflua.WebSockets/Core/WebSocketRouter.cs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,21 +140,22 @@ internal async Task HandleRequest(HttpContext context, CancellationToken cts = d
140140

141141
var path = context.Request.Path.Value;
142142

143-
if (Routes.TryGetValue(path, out var handler))
143+
if (path != null && Routes.TryGetValue(path, out var handler))
144144
{
145145
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
146146
await Task.Run(async () =>
147147
{
148+
IWebSocketClient client = null!;
149+
var webSocketManager = new WebSocketManager();
148150
try
149151
{
150-
var webSocketManager = new WebSocketManager();
151-
var client = new WebSocketClient(context, webSocket, path);
152+
client = new WebSocketClient(context, webSocket, path);
152153
Clients.Add(client);
153154

154155
await Task.Run(async () =>
155156
{
156157
if (_webSocketConfig?.OnOpenHandler != null)
157-
await _webSocketConfig.OnOpenHandler(new WebSocket(webSocket, client, webSocketManager)!, context);
158+
await _webSocketConfig.OnOpenHandler(new WebSocket(webSocket, client, webSocketManager), context);
158159
}, cts);
159160

160161
var buffer = new byte[1024 * 4];
@@ -179,18 +180,26 @@ await handler(
179180
catch (Exception ex)
180181
{
181182
_logger.LogError(message:"Error with handling request: ",exception: ex);
183+
await Task.Run(async () =>
184+
{
185+
if (_webSocketConfig?.OnErrorHandler != null)
186+
await _webSocketConfig.OnErrorHandler(ex, new WebSocket(webSocket, client, webSocketManager), context);
187+
}, cts);
182188
}
183189

184190
}, cts);
185191
}
186192
else
187193
{
188194
context.Response.StatusCode = 404;
195+
throw new KeyNotFoundException("Path not found");
189196
}
190197
}
191198
catch (Exception ex)
192199
{
193200
_logger.LogError(ex, $"Error when handle request {context.Connection.Id}: ");
201+
if (_webSocketConfig!.OnConnectionErrorHandler != null)
202+
await _webSocketConfig.OnConnectionErrorHandler(ex, context);
194203
}
195204
}
196205
}

yawaflua.WebSockets/Models/WebSocketClient.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ internal class WebSocketClient : IWebSocketClient
99
private HttpContext HttpContext { get; set; }
1010
public Guid Id { get; } = Guid.NewGuid();
1111
public string Path { get; }
12-
public ConnectionInfo ConnectionInfo { get => HttpContext.Connection; }
13-
public IDictionary<object, object> Items
12+
public ConnectionInfo ConnectionInfo => HttpContext.Connection;
13+
14+
public IDictionary<object, object>? Items
1415
{
1516
get => HttpContext.Items;
16-
set => HttpContext.Items = (value);
17+
set => HttpContext.Items = value;
1718
}
1819

19-
public HttpRequest HttpRequest { get => HttpContext.Request; }
20+
public HttpRequest HttpRequest => HttpContext.Request;
2021
public WebSocket webSocket { get; }
2122

2223
internal WebSocketClient(HttpContext httpContext, WebSocket webSocket, string path)

yawaflua.WebSockets/ServiceBindings.cs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ namespace yawaflua.WebSockets;
88

99
public static class ServiceBindings
1010
{
11-
public static IServiceCollection SettingUpWebSockets(this IServiceCollection isc, WebSocketConfig? socketOptions = null)
11+
public static IServiceCollection SettingUpWebSockets(this IServiceCollection isc,
12+
WebSocketConfig? socketOptions = null)
1213
{
1314
isc.AddSingleton<WebSocketRouter>();
1415
if (socketOptions != null) isc.AddSingleton(socketOptions);
@@ -19,10 +20,11 @@ public static IServiceCollection SettingUpWebSockets(this IServiceCollection isc
1920
return isc;
2021
}
2122

22-
public static IApplicationBuilder ConnectWebSockets(this IApplicationBuilder iab)
23+
public static IApplicationBuilder UseWebSocketWithSwagger(this IApplicationBuilder app)
2324
{
24-
iab.UseWebSockets();
25-
iab.UseMiddleware<WebSocketMiddleware>();
26-
return iab;
25+
app.UseWebSockets();
26+
app.UseMiddleware<WebSocketMiddleware>();
27+
28+
return app;
2729
}
2830
}

yawaflua.WebSockets/yawaflua.WebSockets.csproj

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@
1919
</PropertyGroup>
2020

2121
<ItemGroup>
22-
<PackageReference Include="JetBrains.Annotations" Version="(2023.3.0,)"/>
23-
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="(2.1.7,)" />
24-
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="(6.0.0,)" />
25-
<PackageReference Include="System.Net.WebSockets" Version="(4.0.0,)"/>
26-
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="(2.2.0,)" PrivateAssets="all">
22+
<PackageReference Include="JetBrains.Annotations" Version=">= (2023.3.0,)"/>
23+
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version=">= (2.1.7,)" />
24+
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version=">= (6.0.0,)" />
25+
<PackageReference Include="System.Net.WebSockets" Version=">= (4.0.0,)"/>
26+
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version=">= (2.2.2,)" PrivateAssets="all">
2727
<Private>False</Private>
2828
</PackageReference>
2929
<None Include="..\README.md" Pack="true" PackagePath="\"/>

0 commit comments

Comments
 (0)