Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Middleware Passing Parameters to Controllers

Tags:

I am using ASP.NET Core Web API, where I have Multiple independent web api projects. Before executing any of the controllers' actions, I have to check if the the logged in user is already impersonating other user (which i can get from DB) and can pass the impersonated user Id to the actions.

Since this is a piece of code that gonna be reused, I thought I can use a middleware so:

  • I can get the initial user login from request header
  • Get the impesonated User Id if any
  • Inject that ID in the request pipeline to make it available to the api being called
public class GetImpersonatorMiddleware {     private readonly RequestDelegate _next;     private IImpersonatorRepo _repo { get; set; }      public GetImpersonatorMiddleware(RequestDelegate next, IImpersonatorRepo imperRepo)     {         _next = next;         _repo = imperRepo;     }     public async Task Invoke(HttpContext context)     {         //get user id from identity Token         var userId = 1;          int impersonatedUserID = _repo.GetImpesonator(userId);          //how to pass the impersonatedUserID so it can be picked up from controllers         if (impersonatedUserID > 0 )             context.Request.Headers.Add("impers_id", impersonatedUserID.ToString());          await _next.Invoke(context);     } } 

I found this Question, but that didn't address what I am looking for.

How can I pass a parameter and make it available in the request pipeline? Is it Ok to pass it in the header or there is more elegant way to do this?

like image 750
Hussein Salman Avatar asked Mar 14 '17 14:03

Hussein Salman


People also ask

What is FromQuery in C#?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.

What is FromBody ASP.NET Core?

The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.

How do I use MapControllerRoute?

MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); The route names give the route a logical name. The named route can be used for URL generation. Using a named route simplifies URL creation when the ordering of routes could make URL generation complicated.


1 Answers

You can use HttpContext.Items to pass arbitrary values inside the pipeline:

context.Items["some"] = "value"; 
like image 96
Ricardo Peres Avatar answered Sep 21 '22 05:09

Ricardo Peres