【问题标题】:Changing property after specific time in ASP Core MVC在 ASP Core MVC 中的特定时间后更改属性
【发布时间】:2021-01-19 04:23:10
【问题描述】:
我正在开发一个使用 Asp Core 3 MVC 和 Sql Server 开发的基于订阅的系统。付款在外部处理,不以任何方式链接到应用程序。我在应用程序中需要做的就是检查用户的状态,这是由管理员管理的。当用户注册时状态为Pending,当管理员批准该用户时,Approval Date将保存在数据库中,状态将更改为已批准。
对我来说棘手的是,我希望应用程序等待 365 天,然后才能将用户状态更改为 已过期。我不知道从哪里开始这部分,希望您能提供帮助。
【问题讨论】:
标签:
asp.net
sql-server
asp.net-core
asp.net-core-mvc
scheduled-tasks
【解决方案1】:
在不使用hosted services 的情况下,我能想到的最简单的方法是添加对用户登录的检查,从今天的日期中减去批准日期,并检查差异是否等于或大于 365 天
类似这样的:
if ((DateTime.Now - user.ApprovalDate).TotalDays >= 365)
{
//Mark the user as expired...
}
【解决方案2】:
您真的不应该从您的主应用程序代码中触发后台线程。
正确的做法是使用专门为此场景设计的background worker process。
ASP.NET Core 3 有一个专门用于此的项目类型,并将继续在后台运行,并可用于您的所有维护任务。您可以使用 dotnet new worker -o YourProjectName 或从 Visual Studio 的项目选择窗口中选择 Worker Service 创建工作进程。
然后,您可以在该服务中创建一个例程,用于确定用户是否已过期。将此逻辑封装在一个使测试变得容易的类中。
工作回复已发布here。
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;
}
}