如何添加所有Razor页面都可以访问的功能? [英] How can I add a function that all Razor Pages can access?

查看:79
本文介绍了如何添加所有Razor页面都可以访问的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Razor Pages ASP.Net Core, I have some functions that I'd like to use on every page. I guess this used to be done with App_Code, but that no longer seems to work in Core. How can I accomplish this in Asp.Net Core Razor Pages?

推荐答案

选项1-

Option 1 - DI

1 - Create the service class with the relevant functionality

public class FullNameService
{
    public string GetFullName(string first, string last)
    {
        return $"{first} {last}";
    }
}

2-在启动时注册服务

2- Register the service in startup

services.AddTransient<FullNameService>();

3-将其注入到剃须刀页面

3- Inject it to the razor page

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-基本模型

1-使用功能创建基本页面模型

Option 2 - Base Model

1- Create a base page model with the function

public class BasePageModel : PageModel
{
    public string GetFullName(string first, string lastName)
    {
        return $"{first} {lastName}";
    }
}

2-从基本模型中导出其他页面

2- Derive other pages from the base model

public class IndexModel : BasePageModel
{
    public string OnGet(string first, string lastName)
    {
        return GetFullName(first, lastName);
    }
}

选项3-

Option 3 - Static Class

1- Use a static function that can be accessed from all pages

public static class FullNameBuilder
{
    public static string GetFullName(string first, string lastName)
    {
        return $"{first} {lastName}";
    }
}

2-从剃须刀页面调用静态功能

2- Call the static function from the razor page

public class IndexModel : PageModel
{
    public string OnGet(string first, string lastName)
    {
        return FullNameBuilder.GetFullName(first, lastName);
    }
}

选项4-扩展方法

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

Option 4 - Extension Methods

1- Create an extension method for a specific type of objects (e.g. string)

public static class FullNameExtensions
{
    public static string GetFullName(this string first, string lastName)
    {
        return $"{first} {lastName}";
    }
}

2-从剃须刀页面拨打扩展名

2- Call the extension from razor page

public class IndexModel : PageModel
{
    public string OnGet(string first, string lastName)
    {
        return first.GetFullName(lastName);
    }
}

这篇关于如何添加所有Razor页面都可以访问的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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