The C# .NET SDK currently only supports legacy versions of Nitric prior to v1. This version is maintained for compatibility with existing projects and not recommended for new projects. New projects should be started using a supported SDK (presented automatically using the `nitric new` command) orget in touch to request an update to the latest version.
.NET - Topic.Subscribe()
Subscribe a handler to a topic and receive new events for processing.
using Nitric.Sdk;
class EventUpdate
{
public string Message { get; set; }
}
var updates = Nitric.Topic<EventUpdate>("updates");
updates.Subscribe(ctx => {
Console.WriteLine(ctx.Req.Payload);
return ctx;
});
Nitric.Run();
Parameters
- Name
middleware
- Required
- Required
- Type
- Func<EventContext, EventContext> or Middleware<EventContext>[]
- Description
The middleware (code) to be triggered by the topic.
Examples
Subscribe to a topic
using Nitric.Sdk;
var updates = Nitric.Topic("updates");
updates.Subscribe(ctx => {
Console.WriteLine(ctx.Req.Payload);
return ctx;
});
Nitric.Run();
Subscibe to a topic with chained middleware
using Nitric.Sdk;
class EventUpdate
{
public string Message { get; set; }
}
var updates = Nitric.Topic<EventUpdate>("updates");
updates.Subscribe((ctx, next) =>
{
// Validate request
if (invalidRequest(ctx))
{
return ctx;
}
return next(ctx);
}, (ctx, next) => {
// Handle request
return next(ctx);
}
);
Nitric.Run();
Notes
- A function may only subscribe to a topic once, if multiple subscribers are required, create them in different functions.
- A function may subscribe to OR publish to a topic but not both