Custom middleware, adding JSON parser #117
-
|
Hey, is it possible to add custom middleware? In my example, I need to parse the request body as JSON, so I don't wanna do it every time in each route, would be great if it can be included as a middleware and an extra string field where it contains a JSON that can be parsed from there, or even a generic parameter specifier that can be passed via attributes or something, so that the body is read as the specified type directly. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
|
Yes. You can parse the JSON in a single place for all your route using In your middleware, after parsing the body, you can add the json to the Here is one sample of how to do this: public static class IRestServerExtensions
{
public static void AutoParseJson(this IRestServer server)
{
server.Router.BeforeRoutingAsync += ParseJsonAsync;
}
public static async Task ParseJsonAsync(IHttpContext context)
{
// Only attempt to parse if the Content-Type header is application/json
// and there is content in the request body
if (context.Request.ContentType != ContentType.Json || !context.Request.HasEntityBody) return;
// Parse your json body using whatever library you choose.
var json = await JsonSerializer.DeserializeAsync<object>(context.Request.InputStream);
// Attached the parsed data to the request locals
context.Locals.TryAdd("your-json-key", json);
}
}You can add this middleware via The places you can attach middleware are:
|
Beta Was this translation helpful? Give feedback.
Yes.
You can parse the JSON in a single place for all your route using
Router.BeforeRoutingAsync. These handlers are delegates of typeRoutingAsyncEventHandler, and run just before any routes are executed (and there is a correspondingrouter.AfterRoutingAsync). This is where you want add your middleware.In your middleware, after parsing the body, you can add the json to the
IHttpRequest.Localsproperty, a key-value store that is used to pass state between all routes for a single request.Here is one sample of how to do this: