Razor Page 的 Catch-all verbs 函数

Catch-all verbs function for Razor Page

对于使用 ASP.NET Core 的 Razor Pages,有什么方法可以为所有动词创建一个包罗万象的处理程序,而不是单独使用 OnGet()、OnPost()。处理程序将需要访问 HttpContext 和 Request 对象(未在构造函数中提供)

而不是

public class ExampleModel : PageModel
{
    public void OnGet()
    {
        //do something
    }

    public void OnPost()
    {
        //do something
    }        
}

类似下面的内容

public class ExampleModel : PageModel
{
    public void OnAll()
    {
        //code executes for POST, PUT, GET, ... VERBS
    }
}

也可以工作只是一些通用的东西,可以在每个请求之前或之后(有上下文)执行

如果要对所有请求方法执行一组命令,可以使用PageModel的构造器:

public class IndexModel : PageModel
{
    public IndexModel()
    {
        // This will be executed first
    }

    public void OnGet()
    {

    }
}

新解

我为您提供了其他解决方案。创建一个将从 PageModel 继承的 class,您将在其中捕获所有不同的请求方法并调用新的虚拟方法。

public class MyPageModel : PageModel
{
    public virtual void OnAll()
    {

    }

    public void OnGet()
    {
        OnAll();
    }
    public void OnPost()
    {
        OnAll();
    }
}

现在更改您的 PageModel class,使其继承您创建的新 class。在您的 class 中,您可以覆盖 OnAll 方法以执行您的公共代码。

public class TestModel : MyPageModel
{
    public override void OnAll()
    {
        // Write your code here
    }
}

Also would work is just something generic that would execute before or after (with context) each request

考虑到以上情况,您可能想要使用过滤器。声明:

public class DefaultFilterAttribute : ResultFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        Console.WriteLine("Here we go");

        base.OnResultExecuted(context);
    }
}

如果您只想在单个页面上看到此行为:

[DefaultFilter]
public class IndexModel : PageModel
{
}

如果您需要在所有页面上应用此过滤器 (Startup.cs):

 services.AddMvcOptions(options =>
            {
                options.Filters.Add(typeof(DefaultFilterAttribute));
            });