6

I am using asp.net core, and I would like to get several data from the request before I call the full web app.

So I created a middleware to do this. I found a way to check everything I want, but I don't know how to pass a variable to the following middlewares

app.Use(async (context, next) => {
    var requestInfo = GetRequestInfo(context.Request);
    if(requestInfo == null)
    {
        context.Response.StatusCode = 404;
        return;
    }

    // How do I make the request info available to the following middlewares ?

    await next();
});

app.Run(async (context) =>
{
    // var requestInfo =  ???
    await context.Response.WriteAsync("Hello World! - " + env.EnvironmentName);
});

Is there a good way to pass data from a middleware to others ? (here I use app.Run, but I would like to have all this in MVC)

glacasa
  • 1,770
  • 2
  • 16
  • 32

2 Answers2

7

Beside features, there is another - a simpler in my opinion - solution: HttpContext.Items, as described here. According to the docs, it is especially designed to store data for the scope of a single request.

Your implementation would look like this:

// Set data:
context.Items["RequestInfo"] = requestInfo;

// Read data:
var requestInfo = (RequestInfo)context.Items["RequestInfo"];
Community
  • 1
  • 1
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
5

I found the solution : the context contains an IFeatureCollection, and it is documented here

We just need to create a class with all the data :

public class RequestInfo
{
    public String Info1 { get; set; }
    public int Info2 { get; set; }
}

And we add it to the context.Features :

app.Use(async (context, next) => {
    RequestInfo requestInfo = GetRequestInfo(context.Request);
    if(requestInfo == null)
    {
        context.Response.StatusCode = 404;
        return;
    }

    // We add it to the Features collection
    context.Features.Set(requestInfo)

    await next();
});

Now it is available to the others middlewares :

app.Run(async (context) =>
{
    var requestInfo = context.Features.Get<RequestInfo>();
});
glacasa
  • 1,770
  • 2
  • 16
  • 32
  • Although this usage is not invalid, I would discourage this usage because Features collection is meant to store server (e.g. Kestrel) related data (e.g. request protocol). Using Items collection in HttpContext is more appropriate, and it has been designed especially for this kind of data transfer across application in a single request. – MÇT Jun 14 '19 at 11:13