Skip to content

engineering87/WART

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

172 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WART - WebApi Real Time

License: MIT Nuget NuGet Downloads issues - wart stars - wart Sponsor me

WART is a lightweight C# .NET library that forwards your Web API calls directly to a SignalR Hub.
It works with both Controllers and Minimal APIs, broadcasting rich, structured events containing request and response details in real-time.
Supports JWT and Cookie Authentication for secure communication.

πŸ“‘ Table of Contents

✨ Features

  • Converts REST API calls into SignalR events, enabling real-time communication.
  • Works with both Controllers and Minimal APIs.
  • Provides controllers (WartController, WartControllerJwt, WartControllerCookie) for automatic SignalR event broadcasting.
  • Provides UseWart() endpoint filter for Minimal API support.
  • Supports JWT authentication for SignalR hub connections.
  • Allows API exclusion from event broadcasting with [ExcludeWart] attribute.
  • Enables group-specific event dispatching with [GroupWart("group_name")].
  • Configurable middleware (AddWartMiddleware) for flexible integration.

πŸ“¦ Installation

Install from NuGet

dotnet add package WART-Core

βš™οΈ How it works

Controllers: WART overrides OnActionExecuting and OnActionExecuted in a custom base controller.
Minimal APIs: WART uses an IEndpointFilter (WartEndpointFilter) that intercepts the request pipeline.

In both cases, for every API request/response:

  1. Captures request and response data.
  2. Wraps them in a WartEvent.
  3. Publishes it through a SignalR Hub to all connected clients.

πŸš€ Usage

Basic Setup

Extend your API controllers from WartController:

using WART_Core.Controllers;
using WART_Core.Hubs;

[ApiController]
[Route("api/[controller]")]
public class TestController : WartController
{
    public TestController(IHubContext<WartHub> hubContext, ILogger<WartController> logger)
        : base(hubContext, logger) { }
}

Register WART in Startup.cs:

using WART_Core.Middleware;

public void ConfigureServices(IServiceCollection services)
{
    services.AddWartMiddleware(); // No authentication
}

public void Configure(IApplicationBuilder app)
{
    app.UseWartMiddleware();
}

Using JWT Authentication

services.AddWartMiddleware(hubType: HubType.JwtAuthentication, tokenKey: "your_secret_key");
app.UseWartMiddleware(HubType.JwtAuthentication);

Extend from WartControllerJwt:

public class TestController : WartControllerJwt
{
    public TestController(IHubContext<WartHubJwt> hubContext, ILogger<WartControllerJwt> logger)
        : base(hubContext, logger) { }
}

Custom Hub Names

You can specify custom hub routes:

app.UseWartMiddleware("customhub");

Multiple Hubs

You can configure multiple hubs at once by passing a list of hub names:

var hubs = new[] { "orders", "products", "notifications" };

app.UseWartMiddleware(hubs);

This is useful for separating traffic by domain.

Client Example

Without authentication:

var hubConnection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5000/warthub")
    .Build();

hubConnection.On<string>("Send", data =>
{
    // 'data' is a WartEvent JSON
});

await hubConnection.StartAsync();

With JWT authentication:

var hubConnection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5000/warthub", options =>
    {
        options.AccessTokenProvider = () => Task.FromResult(GenerateToken());
    })
    .WithAutomaticReconnect()
    .Build();

hubConnection.On<string>("Send", data =>
{
    // Handle WartEvent JSON
});

await hubConnection.StartAsync();

πŸ”Œ Minimal API Support

WART fully supports Minimal APIs via the UseWart() endpoint filter extension method. No base controller is needed.

Basic usage

using WART_Core.Middleware;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddWartMiddleware();

var app = builder.Build();
app.UseWartMiddleware();

app.MapGet("/api/items", () => new[] { "item1", "item2" })
   .UseWart();

app.MapPost("/api/items", (Item item) => item)
   .UseWart();

app.Run();

Applying to a route group

You can apply WART to all endpoints in a group at once:

var group = app.MapGroup("/api/v2").UseWart();
group.MapGet("/orders", () => GetOrders());
group.MapPost("/orders", (Order o) => CreateOrder(o));

Excluding endpoints

app.MapGet("/api/health", () => "ok")
   .UseWart()
   .ExcludeFromWart();

Group-based dispatching

app.MapPost("/api/orders", (Order o) => CreateOrder(o))
   .UseWart()
   .WartGroup("admin", "managers");

πŸ’‘ The ExcludeWart and GroupWart attributes work as endpoint metadata for Minimal APIs and as action filters for controllers β€” no breaking changes.

πŸ” Supported Authentication Modes

Mode Description Hub Class Required Middleware
No Authentication Open access without identity verification WartHub None
JWT (Bearer Token) Authentication via JWT token in the Authorization: Bearer <token> header WartHubJwt UseJwtMiddleware()
Cookie Authentication Authentication via HTTP cookies issued after login WartHubCookie UseCookieMiddleware()

βš™οΈ Authentication mode is selected through the HubType configuration in the application startup.

🚫 Excluding APIs from Event Propagation

There might be scenarios where you want to exclude specific APIs from propagating events to connected clients. This can be particularly useful when certain endpoints should not trigger updates, notifications, or other real-time messages through SignalR. To achieve this, you can use a custom filter called ExcludeWartAttribute. By decorating the desired API endpoints with this attribute, you can prevent them from being included in the SignalR event propagation logic, for example:

[HttpGet("{id}")]
[ExcludeWart]
public ActionResult<TestEntity> Get(int id)
{
    var item = Items.FirstOrDefault(x => x.Id == id);
    if (item == null)
    {
        return NotFound();
    }
    return item;
}

πŸ‘₯ Group-based Event Dispatching

WART enables sending API events to specific groups in SignalR by specifying the group name in the query string. This approach allows for flexible and targeted event broadcasting, ensuring that only the intended group of clients receives the event. By decorating an API method with [GroupWart("group_name")], it is possible to specify the SignalR group name to which the dispatch of specific events for that API is restricted. This ensures that only the clients subscribed to the specified group ("SampleGroupName") will receive the related events, allowing for targeted, group-based communication in a SignalR environment.

[HttpPost]
[GroupWart("SampleGroupName")]
public ActionResult<TestEntity> Post([FromBody] TestEntity entity)
{
    Items.Add(entity);
    return entity;
}

By appending ?WartGroup=group_name to the URL, the library enables dispatching events from individual APIs to a specific SignalR group, identified by group_name. This allows for granular control over which clients receive the event, leveraging SignalR’s built-in group functionality.

πŸ“¦ NuGet

The library is available on NuGet.

🀝 Contributing

Contributions are welcome! Steps to get started:

πŸ“„ License

WART source code is available under MIT License, see license in the source.

πŸ“¬ Contact

Please contact at francesco.delre[at]protonmail.com for any details.

About

Transforms REST APIs into SignalR events, bringing real-time interaction to your applications.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors