I'm migrating my ASP.Net app to ASP.Net core and one feature that I have is that all my controllers inherit from a base controller in which I do:
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
string token = controllerContext.Request.Properties["token"] as string;
user = UserCache.Get(token);
//Called by derived controllers
//to set their repository user
SetInfo();
}
Do I need to move the above code to middleware? Will the middleware allow me to set call the controllers' SetInfo() method?
In the first part, it looks like you are extracting a token for authentication purpose. A middleware could be configured to run before your controller action, but it's a matter of how to pass information to your controller. For instance an authentication middleware would simply set the Principal of your HttpRequest that could then be reused during your controller execution.
Regarding the SetInfo, if clearly depends on the nature of the information whether it's a good idea or not to use a middleware to do it, but it's doable. For instance, in my case, for debugging reason in dev, I have a middleware transmitting the information of when will my session expires to my controller by adding it in the HttpContext. I'm not saying it's a good practice though.
context.Request.HttpContext.Items.Add(ExpiresUTCEntry, context.Properties.ExpiresUtc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With