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

查看:75
本文介绍了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#中的每个请求中运行方法?

或这个

@ Html.Asp.Net Core中的操作

运行,不确定是否是因为它们不是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
         }
  }

然后在ConfigureServices方法的Startup.cs文件中,将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天全站免登陆