-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
71 lines (53 loc) · 1.99 KB
/
Program.cs
File metadata and controls
71 lines (53 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyCompany("Eugene Fox")]
[assembly: AssemblyCopyright("© Eugene Fox 2025")]
WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
policy
.SetIsOriginAllowed(_ => true)
.WithMethods(["POST"])
.WithHeaders(["x-requested-with", "x-signalr-user-agent"])
.AllowCredentials());
});
WebApplication app = builder.Build();
app.UseCors();
app.MapHub<WsHub>("/ws", options =>
{
options.ApplicationMaxBufferSize = 1; // 1B, virtually disabling ability for clients to send data
});
app.MapPost("/send",
static async (
[FromServices] IHubContext<WsHub> hubContext,
[FromServices] ILogger<Program> logger,
HttpContext context
) =>
{
string? id = context.Request.Query["id"].FirstOrDefault();
// Id validation
if (string.IsNullOrEmpty(id) || id.Length > 32)
return Results.StatusCode(StatusCodes.Status400BadRequest);
foreach (char c in id)
if (!char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_'))
return Results.StatusCode(StatusCodes.Status400BadRequest);
// Content validation
if (context.Request.ContentType is not "text/plain")
return Results.StatusCode(StatusCodes.Status415UnsupportedMediaType);
if (context.Request.ContentLength is < 1 or > 66_560)
return Results.StatusCode(StatusCodes.Status400BadRequest);
// Sending data
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Received payload for connection '{id}' (package length: {len} B)", id, context.Request.ContentLength);
using StreamReader reader = new(context.Request.Body);
string? data = await reader.ReadToEndAsync();
await hubContext.Clients.Client(id).SendAsync("OnMessage", data);
return Results.Ok();
}
);
app.Run();
class WsHub : Hub { }