I want to know if is it possible to send value from middleware to controllerAPI ?
For example, I want catch one particular header and send to the controller.
Something like that :
public class UserTokenValidatorsMiddleware
{
private readonly RequestDelegate _next;
//private IContactsRepository ContactsRepo { get; set; }
public UserTokenValidatorsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Path.Value.Contains("auth"))
{
if (!context.Request.Headers.Keys.Contains("user-token"))
{
context.Response.StatusCode = 400; //Bad Request
await context.Response.WriteAsync("User token is missing");
return;
}
// Here I want send the header to all controller asked.
}
await _next.Invoke(context);
}
}
#region ExtensionMethod
public static class UserTokenValidatorsExtension
{
public static IApplicationBuilder ApplyUserTokenValidation(this IApplicationBuilder app)
{
app.UseMiddleware<UserTokenValidatorsMiddleware>();
return app;
}
}
#endregion
What I did was making use of these things:
ActionFilterAttribute
(because I have access to the IDependencyResolver)HierarchicalLifetimeManager
(so I get a new instance per request)(Read about dependency scope)Action filter
TokenProvider
Unity configuration
Controller
UPDATE
For asp.net core use the builtin DI container. Register the
TokenProvider
as Transient to get a new one per request: