MVC CORE 2.0.0 在每一页上运行 c# 代码 [英] MVC CORE 2.0.0 run c# code on every page

查看:11
本文介绍了MVC CORE 2.0.0 在每一页上运行 c# 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次查看任何基于 _layout.cshtml 的页面时,我都需要运行一些 c# 代码.我不想在每个 controller.cs 文件中都放一些东西,只是像你以前在 ASP.NET 的 MasterPage.cs 中那样放一些中心

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

找不到这个

在MVC,C#中的每个请求中运行一个方法?

或者这个

Asp.Net Core 中的@Html.Action

运行,不确定是不是因为它们不是 CORE 2.0.0,我只是得到很多编译错误.我想做的就是能够运行一些这样的代码

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;
    }
}

每次加载每个页面.

推荐答案

您可以使用操作过滤器完成此操作

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
         }
  }

然后在 Startup.cs 文件中的 ConfigureServices 方法中连接 ActionFilter,如下所示:

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
 });

然后您可以在此 ActionFilter 中放置代码,它可以在每个操作方法之前运行,您可以在其中放置代码以在每个操作方法之后运行.请参阅代码注释.

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.

通过 context 参数,您可以访问控制器、控制器名称、动作描述符、动作名称、请求对象(包括路径)等,因此有很多信息可供您使用来确定要为哪个页面执行代码.我不知道一个特定的属性会告诉你页面是否正在使用 _layout.cshtml 但你可能会根据我提到的其他属性推断出来.

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.

享受吧.

这篇关于MVC CORE 2.0.0 在每一页上运行 c# 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆