Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to create a custom context object in middleware and access it in the controller

$
0
0

If I want to build a "custom context" in a piece of middleware:

public class MyCustomMiddleware
{
    private RequestDelegate _next;

    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;

    }//ctor

    public async Task Invoke(HttpContext context)
    {

        //COMPOSE MY CUSTOM CONTEXT HERE
	MyCustomContext ctx = new MyCustomContext();
        ...
	...
        await _next(context);

    }//Invoke()

}//MyCustomMiddleware

I then want that context to be available in a controller. Do I need to create a service to do That?

public void ConfigureServices(IServiceCollection services)
{
    //Add MVC and Camel Casing for Json
    services.AddMvc()
                .AddJsonOptions(opt => {
                    opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });

    //DO I CREATE A SERVICE?? Like
    //services.AddMyCustoMiddlewareService();

}//ConfigureServices()

public void Configure(IApplicationBuilder app)
{
    app.UseMvcWithDefaultRoute();
    app.UseMyCustomMiddleware();

}//Configure()

How Can I get a reference to that custom context I created in the middleware in a controller?

thanks in advance!


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>