AzureFunctions.Extensions.Middleware 1.0.0

.NET 5.0 .NET Core 3.1
There is a newer version of this package available.
See the version list below for details.
dotnet add package AzureFunctions.Extensions.Middleware --version 1.0.0
NuGet\Install-Package AzureFunctions.Extensions.Middleware -Version 1.0.0
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.Middleware" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AzureFunctions.Extensions.Middleware --version 1.0.0
#r "nuget: AzureFunctions.Extensions.Middleware, 1.0.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install AzureFunctions.Extensions.Middleware as a Cake Addin
#addin nuget:?package=AzureFunctions.Extensions.Middleware&version=1.0.0

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

<div id=top></div> <h1 align="center"><a href="https://iamdivakarkumar.com/" target="blank"><img height="240" src="./icons/middleware.png"/><br/>AzureFunctions.Extensions.Middleware</a></h1>

<p align="center"> <b>.NET library that allows developers to implement middleware pattern in Azure functions (In-Process Mode) </b> </p>

<p align="center">

<a href="https://ci.appveyor.com/project/kroniak/flurl/branch/master"> <img src="https://ci.appveyor.com/api/projects/status/hec8ioqg0j07ttg5/branch/master?svg=true" alt="Build status"/> </a>

<a href="https://www.nuget.org/packages/AzureFunctions.Extensions.Middleware"> <img src="https://img.shields.io/nuget/v/AzureFunctions.Extensions.Middleware.svg" alt="Middleware version"/> </a>

<a href="https://www.nuget.org/packages/AzureFunctions.Extensions.Middleware"> <img src="https://img.shields.io/nuget/dt/AzureFunctions.Extensions.Middleware.svg" alt="Middleware downloads"/> </a>

</p>

<p align="center"> <a href="#features">Features</a> | <a href="#sample">Sample</a> | <a href="#installation">Installation</a> | <a href="#usage">Usage</a> | <a href="#special-thanks">Special Thanks</a> | <a href="https://github.com/cloud-jas/AzureFunctions.Extensions.Middleware/discussions">Forum</a> </p>

<br/>

<details> <summary>Table of Contents</summary> <ol> <li> <a href="#features">Features</a>
</li> <li><a href="#Supported-Frameworks">Supported frameworks</a></li> <li> <a href="#installation">Getting Started</a>
</li> <li><a href="#usage">Usage</a></li> <li><a href="#roadmap">Roadmap</a></li> <li><a href="#sponsor">Sponsor</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#acknowledgments">Acknowledgments</a></li> </ol> </details>

Features

  • Able to add multiple custom middlewares to the pipeline
  • Able to access HTTP context inside the custom middleware
  • Able to bypass middlewares and return response
  • Handle Crosscutting concerns of the application
    • Logging
    • Exception Handling
    • CORS
    • Performance Monitoring
    • Caching
    • Security
  • Licenced under MIT - 100% free for personal and commercial use

Supported Frameworks

  • NetCoreApp 3.1
  • NET 5.0
  • NET 6.0

<p align="right">(<a href="#top">back to top</a>)</p>

Installation

Install with Package Manager Console

PM> Install-Package AzureFunctions.Extensions.Middleware

Usage

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. Add custom middlewares to the pipeline

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


builder.Services.AddTransient<IMiddlewareBuilder, MiddlewareBuilder>((serviceProvider) =>
            {
                var funcBuilder = new MiddlewareBuilder(serviceProvider.GetRequiredService<IHttpContextAccessor>());
                funcBuilder.Use(new ExceptionHandlingMiddleware(new LoggerFactory().CreateLogger(nameof(ExceptionHandlingMiddleware))));
                funcBuilder.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api/Authorize"),
                    new AuthorizationMiddleware(new LoggerFactory().CreateLogger(nameof(AuthorizationMiddleware))));
                return funcBuilder;
            });

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.

3. IMiddlewareBuilder dependency

We can now add IMiddlewareBuilder as a dependency to our HTTP trigger function class.


        private readonly ILogger<Function1> _logger;
        private readonly IMiddlewareBuilder _middlewareBuilder;

        public Function1(ILogger<Function1> log, IMiddlewareBuilder middlewareBuilder)
        {
            _logger = log;            
            _middlewareBuilder = middlewareBuilder;
        }

4. Execute 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 _middlewareBuilder.ExecuteAsync(new FunctionsMiddleware(async (httpContext) =>
            {
                _logger.LogInformation("C# HTTP trigger function processed a request.");

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

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

                string responseMessage = string.IsNullOrEmpty(name)
                    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                    : $"Hello, {name}. This HTTP triggered function executed successfully.";

                return new OkObjectResult(responseMessage);
            }));

<p align="right">(<a href="#top">back to top</a>)</p>

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.

Special Thanks

Thank you to the following people for their support and contributions!

Leave a ⭐ if this library helped you at handling cross-cutting concerns in serverless architecture.

<a href="https://www.buymeacoffee.com/divakarkumar" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145 !important;" ></a>

Website | LinkedIn | Forum | Contribution Guide | Donate | License

© Divakar Kumar

For detailed documentation, please visit the docs.

Contact

Nuget library screenshot

Divakar Kumar - @Divakar-Kumar - https://iamdivakarkumar.com

Project Link: https://github.com/Cloud-Jas/AzureFunctions.Extensions.Middleware

<p align="right">(<a href="#top">back to top</a>)</p>

Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp3.1
Compatible target framework(s)
Additional computed target framework(s)
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
3.0.0 2,850 7/20/2022
2.1.0 1,772 6/21/2022
2.0.1 253 6/9/2022
2.0.0 247 6/9/2022
1.0.2 1,114 1/16/2022
1.0.0 257 1/16/2022