CSharp Web API Concepts

From bibbleWiki
Revision as of 23:42, 21 November 2024 by Iwiseman (talk | contribs) (Created page with "=Introduction= This pages is to capture some useful thing around the Web API. =Middleware= I was trying to match up my Typescript work with C# so I started off be looking a middleware. Not a difficult concept. So for .NET 8.0 for me it consisting of *Making and Extension *Applying the extension *Implementing the middleware Pretty straight forward <syntaxhighlight lang="cs"> // Create an extension public static IApplicationBuilder UseCustomMiddleware(this IApplication...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

This pages is to capture some useful thing around the Web API.

Middleware

I was trying to match up my Typescript work with C# so I started off be looking a middleware. Not a difficult concept. So for .NET 8.0 for me it consisting of

  • Making and Extension
  • Applying the extension
  • Implementing the middleware

Pretty straight forward

// Create an extension
    public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder app)
    {
        return app.UseMiddleware<CustomMiddleware>();
    }

// Applying the extension
...
        var app = builder.Build();

        app.UseCustomMiddleware();

        app.MapGet("/", (HttpContext context) =>
        {
            return "Hello World!";
        });
...

// Implementing the middleware
public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine($"Request: {context.Request.Path}");
        await _next(context);
    }
}