使用Razor页面ASP.Net Core,我想在每个页面上使用一些功能。我猜想这曾经是用App_Code完成的,但是似乎在Core中不再起作用了。如何在Asp.Net Core Razor页面中完成此操作?
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);
}
}
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);
}
}
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);
}
}
1-为特定类型的对象(例如字符串)创建扩展方法
public static class FullNameExtensions
{
public static string GetFullName(this string first, string lastName)
{
return $"{first} {lastName}";
}
}
2-调用剃刀页面扩展名
public class IndexModel : PageModel
{
public string OnGet(string first, string lastName)
{
return first.GetFullName(lastName);
}
}