Hooking into razor page execution for ASP.Net Core

白昼怎懂夜的黑 提交于 2020-01-02 10:04:11

问题


I'm trying to hook into the ExecuteAsync() call that renders a razor page using my CUSTOM view page (that inherits from RazorPage). In the RazorPage class there is this abstract method:

public abstract Task ExecuteAsync();

That method gets called within the output generated by razor when parsing a .cshtml file (view).

Obviously, I cannot just override it because mine would never get called from the view that gets generated, which also overrides this method (though that would be nice, and solve at least part of the problem).

Is there any special razor tricks in .Net core where I can intercept before AND after the rendering process? (using my custom class that is)


回答1:


Ok, looks like you have to use ViewResultExecutor. After more spelunking through the code, I found that an executor was used to call the first ExecuteAsync() in a chain of nested ExecuteAsync calls. ;)

public class MyViewResultExecutor : ViewResultExecutor
{
    ....
    public override Task ExecuteAsync(ActionContext actionContext, IView view, ViewResult viewResult) ....
    ....
}
....
services.TryAddSingleton<ViewResultExecutor, MyViewResultExecutor>();

The ViewResultExecutor service object is obtained in ViewResult.ExecuteResultAsync(ActionContext context).

The great thing is you can also access your custom page type through the view parameter ((view as RazorView)?.RazorPage). ;) (though, of course, you'll have to cast it to your custom type)

(I started a discussion here originally if anyone is interested to read a few more details on the ASP.Net Core MVC Source side of things)

Update: This process has changed since this was originally posted. This is the new way to register your own executor:

services.TryAddSingleton<IActionResultExecutor<ViewResult>, MyViewResultExecutor>();
// ... or ...
services.TryAddSingleton<IActionResultExecutor<PartialViewResult>, MyPartialViewResultExecutor>();

Please notice the TryAdd part. That means it will not add it if it already exists. This is the same thing the MVC code tries to do, so you must register yours FIRST before MVC does. Also, if deriving from ViewResultExecutor (instead of the interface it implements) the {ViewResultExecutor}.ExecuteAsync(...) signature has changed and can no longer be overridden. You can only override the base {ViewExecutor}.ExecuteAsync(...) method now.



来源:https://stackoverflow.com/questions/43267839/hooking-into-razor-page-execution-for-asp-net-core

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