如何添加所有 Razor 页面都可以访问的功能?

Posted

技术标签:

【中文标题】如何添加所有 Razor 页面都可以访问的功能?【英文标题】:How can I add a function that all Razor Pages can access? 【发布时间】:2020-05-26 06:17:19 【问题描述】:

使用 Razor Pages ASP.Net Core,我有一些我想在每个页面上使用的功能。我想这曾经是用 App_Code 完成的,但这似乎不再适用于 Core。如何在 Asp.Net Core Razor Pages 中完成此操作?

【问题讨论】:

服务注入对您有用吗? docs.microsoft.com/en-us/aspnet/core/mvc/views/… 【参考方案1】:

选项 1 - DI

1 - 创建具有相关功能的服务类

public class FullNameService

    public string GetFullName(string first, string last)
    
        return $"first last";
    

2- 在启动时注册服务

services.AddTransient<FullNameService>();

3- 将其注入剃须刀页面

public class IndexModel : PageModel

    private readonly FullNameService _service;

    public IndexModel(FullNameService service)
    
        _service = service;
    

    public string OnGet(string name, string lastName)
    
        return _service.GetFullName(name, lastName);
    

选项 2 - Base Model

1- 使用函数创建基本页面模型

public class BasePageModel : PageModel

    public string GetFullName(string first, string lastName)
    
        return $"first lastName";
    

2- 从基本模型派生其他页面

public class IndexModel : BasePageModel

    public string OnGet(string first, string lastName)
    
        return GetFullName(first, lastName);
    

选项 3 - Static Class

1-使用可以从所有页面访问的静态函数

public static class FullNameBuilder

    public static string GetFullName(string first, string lastName)
    
        return $"first lastName";
    

2- 从剃须刀页面调用静态函数

public class IndexModel : PageModel

    public string OnGet(string first, string lastName)
    
        return FullNameBuilder.GetFullName(first, lastName);
    

选项 4 - Extension Methods

1- 为特定类型的对象(例如字符串)创建扩展方法

public static class FullNameExtensions

    public static string GetFullName(this string first, string lastName)
    
        return $"first lastName";
    

2- 从 razor 页面调用扩展

public class IndexModel : PageModel

    public string OnGet(string first, string lastName)
    
        return first.GetFullName(lastName);
    

【讨论】:

以上是关于如何添加所有 Razor 页面都可以访问的功能?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Razor Pages 路由的开头添加应用程序名称?

如何从 Blazor WebAssembly 中的 Razor 页面访问 body 标签或其他标签?

关于后台管理的所有页面都放在Admin文件夹下,在Pages文件夹下新建Admin文件夹

如何将配置设置添加到 _Layout.cshtml 共享 Razor 页面

如何在 Razor 页面模型中使用泛型类型

当 API 调用完成时,如何从 .RAZOR 主页面中的所有子组件触发/刷新我的主 .RAZOR 页面?