MVC CORE 2.0.0 run c# code on every page

孤者浪人 提交于 2019-12-01 12:03:30

问题


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 you used to have in ASP.NET's MasterPage.cs

Can't get this

Run a method in each request in MVC, C#?

or this

@Html.Action in Asp.Net Core

to run, not sure if it's because they're not CORE 2.0.0, I just get a lot of compilation errors. All I want to do is be able to run some code like this

public class myClass {
    public static bool returnTrue() {
        return true;
    }
}

every time each page is loaded.


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/47397756/mvc-core-2-0-0-run-c-sharp-code-on-every-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!