Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

asp.net core - How can I add a function that all Razor Pages can access?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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- Register the service in startup

services.AddTransient<FullNameService>();

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);
    }
}

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- Derive other pages from the base model

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

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- Call the static function from the razor page

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

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- Call the extension from razor page

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...