asp.net - 在 ASP Core MVC 中的特定时间后更改属性
问题描述
我正在开发一个使用 Asp Core 3 MVC 和 Sql Server 开发的基于订阅的系统。付款在外部处理,不以任何方式链接到应用程序。我在应用程序中需要做的就是检查由管理员管理的用户状态。当用户注册时,状态为Pending,当管理员批准用户时,Approval Date将保存在数据库中,状态将更改为Approved。
对我来说棘手的是我希望应用程序等待 365 天,然后才能将用户状态更改为Expired。我不知道从哪里开始这部分,并感谢您的帮助。
解决方案
您真的不应该从您的主应用程序代码中触发后台线程。
正确的方法是使用专门为此场景设计的后台工作进程。
ASP.NET Core 3 有一个专门为此而设计的项目类型,它将继续在后台运行,并可用于您的所有维护任务。dotnet new worker -o YourProjectName
您可以使用或从 Visual Studio 的项目选择窗口中选择Worker Service来创建工作进程。
然后,您可以在该服务中创建一个例程,用于确定用户是否已过期。将此逻辑封装在一个使测试变得容易的类中。
工作 repl 已在此处发布。
using System;
public class MainClass {
public static void Main (string[] args) {
var user = new User(){ ApprovedDate = DateTime.Today };
Console.WriteLine (UserHelper.IsUserExpired(user));
// this should be false
user = new User(){ ApprovedDate = DateTime.Today.AddDays(-180) };
Console.WriteLine (UserHelper.IsUserExpired(user));
// this should be false
user = new User(){ ApprovedDate = DateTime.Today.AddDays(-365) };
Console.WriteLine (UserHelper.IsUserExpired(user));
// this should be true
user = new User(){ ApprovedDate = DateTime.Today.AddDays(-366) };
Console.WriteLine (UserHelper.IsUserExpired(user));
}
}
public class User {
public DateTime ApprovedDate {get; set;}
}
public static class UserHelper
{
public static bool IsUserExpired(User user){
//... add all the repective logic in here that you need, for example;
return (DateTime.Today - user.ApprovedDate.Date).TotalDays > 365;
}
}
推荐阅读
- windows - 远程位置的文件访问检查
- android - 在 Android 中从 alpha、red、green、blue 创建颜色 int
- windows - 无法拉取 nanoserver:1903 Docker 映像
- c# - 如何在asp.net核心中获取查询字符串参数值?
- modelica - 根据连续变量的开始/初始值设置参数
- swift - 具有自定义操作的 TabBar 控制器
- angularjs - 如何为检查 2 个密码是否匹配的指令编写单元测试?
- php - 如何使用 PHP 从字符串中提取数字(例如,西红柿:10)
- c# - 使文本框接受一种语言
- excel - Copying Multiple Ranges to Next Available Row