MVC CORE 2.0.0 run c# code on every page

后端 未结 2 2015
你的背包
你的背包 2021-01-07 11:00

I need to run some c# code each time any page based on _layout.cshtml is viewed. I don\'t want to put something in every controller.cs file, just something central like yo

相关标签:
2条回答
  • 2021-01-07 11:52

    You can accomplish this with an action filter

      public class GlobalFilter : IActionFilter{
    
             public void OnActionExecuting(ActionExecutingContext context) {
                 //code here runs before the action method executes
             }
    
             public void OnActionExecuted(ActionExecutedContext context) {
                  //code here runs after the action method executes
             }
      }
    

    Then in the Startup.cs file in the ConfigureServices method you wire up the ActionFilter like so:

    services.AddScoped<GlobalFilter>();                //add it to IoC container.
    services.AddMvc().AddMvcOptions(options => {
         options.Filters.AddService(typeof(GlobalFilter));  //Tell MVC about it
     });
    

    Then you can place code in this ActionFilter which can run before every action method and you can place code in it to run after every action method. See code comments.

    Through the context parameter you have access to the Controller, Controller Name, Action Descriptor, Action Name, Request object (Including the path) and so on, so there is lots of info available for you to determine which page you want to execute the code for. I'm not aware of a specific property that will tell you if the page is using _layout.cshtml but you could probably deduce that based on the other properties I mentioned.

    Enjoy.

    0 讨论(0)
  • 2021-01-07 11:56

    Filter would also work, but the correct way to go in .Net Core is Middleware. You can read more about it here.

    If it's something simple as your example, you can go with the first examples on the link like:

    app.Use(async (context, next) =>
            {
                returnTrue();
                await next.Invoke();
            });
    

    Let me know if it helped!

    0 讨论(0)
提交回复
热议问题