首页 > 解决方案 > 在 ASP Core MVC 中的特定时间后更改属性

问题描述

我正在开发一个使用 Asp Core 3 MVC 和 Sql Server 开发的基于订阅的系统。付款在外部处理,不以任何方式链接到应用程序。我在应用程序中需要做的就是检查由管理员管理的用户状态。当用户注册时,状态为Pending,当管理员批准用户时,Approval Date将保存在数据库中,状态将更改为Approved

对我来说棘手的是我希望应用程序等待 365 天,然后才能将用户状态更改为Expired。我不知道从哪里开始这部分,并感谢您的帮助。

标签: asp.netsql-serverasp.net-coreasp.net-core-mvcscheduled-tasks

解决方案


您真的不应该从您的主应用程序代码中触发后台线程。

正确的方法是使用专门为此场景设计的后台工作进程。

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

推荐阅读