AzureFunctions.Extensions.HttpMiddleware 1.0.1

dotnet add package AzureFunctions.Extensions.HttpMiddleware --version 1.0.1
NuGet\Install-Package AzureFunctions.Extensions.HttpMiddleware -Version 1.0.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AzureFunctions.Extensions.HttpMiddleware" Version="1.0.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AzureFunctions.Extensions.HttpMiddleware --version 1.0.1
#r "nuget: AzureFunctions.Extensions.HttpMiddleware, 1.0.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install AzureFunctions.Extensions.HttpMiddleware as a Cake Addin
#addin nuget:?package=AzureFunctions.Extensions.HttpMiddleware&version=1.0.1

// Install AzureFunctions.Extensions.HttpMiddleware as a Cake Tool
#tool nuget:?package=AzureFunctions.Extensions.HttpMiddleware&version=1.0.1

Supported Frameworks

  • NetCoreApp 3.1
  • NET 5.0
  • NET 6.0

Installation

PM> Install-Package AzureFunctions.Extensions.HttpMiddleware

Getting Started

1. Add HttpContextAccessor to service collection

Inorder to access/modify HttpContext within custom middleware we need to add HttpContextAccessor in Startup.cs file.


builder.Services.AddHttpContextAccessor();

2. Register custom middlewares to the pipeline

One or more custom middlewares can be added to the execution pipeline using MiddlewareBuilder.


public IMiddlewarePipeline Add(Func<HttpContext, Task<IActionResult>> func)
        {
            MiddlewarePipeline pipeline = new MiddlewarePipeline(this.httpContextAccessor);

            // If Function1 is called, then use custom middleware.
            return pipeline.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/api/Function1"),
                                     p => p.Use(async context => {
                                         await context.Response.WriteAsync("hello custom middleware");
                                     }));
        }

2.1 Use()

  • Use() middleware takes custom middleware as parameter and will be applied to all the endpoints

2.2 UseWhen()

  • UseWhen() takes Func<HttpContext, bool> and custom middleware as parameters. If the condition is satisfied then middleware will be added to the pipeline of exectuion.

2.3 Map()

  • Map() middleware takes custom middleware as parameter and will be applied to all the endpoints . Map Enables branching pipeline. Runs specified middleware if the condition is met.

2.4 MapWhen()

  • MapWhen() takes Func<HttpContext, bool> and custom middleware as parameters. MapWhen also fulfills the same purpose with better control on mapping conditional logic using the predicates, this extension doesn't stop executing the rest of the pipeline when the delegate returns true, which makes "conditional middleware execution.

3. RunAsync pipeline

Now we need to bind last middleware for our HttpTrigger method , to do that wrap our existing code inside Functionsmiddleware block "_middlewareBuilder.ExecuteAsync(new FunctionsMiddleware(async (httpContext) ⇒{HTTP trigger code})"

 
return await _pipelineFactory.Add(async (context) =>
            {
                this._logger.LogInformation("C# HTTP trigger function processed a request.");

                string name = context.Request.Query["name"];

                string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;

                string responseMessage = string.IsNullOrEmpty(name)
                    ? "This HTTP triggered function executed successfully."
                    : $"Hello, {name}. This HTTP triggered function executed successfully.";

                return new OkObjectResult(responseMessage);
            }).RunAsync();

Sample

You can find .NET 6 sample application here . In this example we have registered Exception handling custom middleware to the exectuion order that will handle any unhandled exceptions in the Http Trigger execution.

Contributors ✨

Saurav Singh

Support

Leave ⭐ if this library helped you at handling custom middleware.

Website | LinkedIn | Forum | Contribution Guide | License

© Saurav Singh

Contact

Saurav Singh - @beingsrvsingh - https://codexpo.in

Referances

© umamimolecule

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.1 3,767 2/8/2022
1.0.0 552 1/29/2022

Handle multiple custom middleware to requrest in the pipeline.
Handle Use, UseWhen, Map, MapWhen middleware to request in the pipeline branch.