Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use middleware to instead of controller initialize?

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?

like image 326
Ivan-Mark Debono Avatar asked Nov 08 '22 01:11

Ivan-Mark Debono


1 Answers

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);
like image 177
Daboul Avatar answered Nov 14 '22 22:11

Daboul