限制在一年中的特定时间访问页面

Restricting access to page to certain times of the year

是否可以对我的 ASP.NET MVC 应用程序实施某种限制,当用户在受限时间尝试访问视图时,它将重定向到不同的视图。

我知道有一种方法可以使用 .htaccess 和一个简单的 if/else 语句来做到这一点,而且我也知道 URL 在 WebConfig.cs 文件中重定向,但究竟如何我可以在我的 ASP.NET MVC 应用程序中实现它吗?

感谢您的宝贵时间。

编辑 到目前为止,我在@dekanidze

的帮助下所做的工作

属性 (TimeLim.cs)

 public class TimeLim : ActionFilterAttribute
    {
        public TimeLim() { }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (DateTime.Now.Date > new DateTime(2021, 3, 1) && DateTime.Now.Date <= new DateTime(2021, 3, 31)
                || DateTime.Now.Date > new DateTime(2021, 10, 1) && DateTime.Now.Date <= new DateTime(2021, 10, 7))
            {
                filterContext.Result = new RedirectToRouteResult(
                    new System.Web.Routing.RouteValueDictionary(
                        new
                        {
                            controller = "TimeLim", //input right one
                            action = "PageNotAvailable" //input right one
                        })
                    );
            }
        }
    }

TimeLimController

public class TimeLimController : Controller
    {
        // GET: TimeLim
        [AllowAnonymous]
        public ActionResult PageNotAvailable()
        {
            return View();
        }
    }

查看(PageNotAvailable)

@{
    ViewBag.Title = "PageNotAvailable";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row">
    <div class="col-md-12">
        <h1>PageNotAvailable</h1>
       

        <p> Sorry, but this page is not available right now. Please come back 1 March, or 1 October. </p>
    </div>
</div>

创建您自己的自定义过滤器属性怎么样?下面的代码将在调用操作方法之前执行。

UPDATE:根据OP评论更新代码:

public class MyCustomAttribute : ActionFilterAttribute
{
    public MyCustomAttribute() { }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       
        DateTime dateToCheck1 = new DateTime(2021, 03, 01);
        DateTime dateToCheck2 = new DateTime(2021, 10, 01);

        if ((DateTime.Now.Date > dateToCheck1 && DateTime.Now.Date < dateToCheck1.AddDays(7)) 
            || (DateTime.Now.Date > dateToCheck2 && DateTime.Now.Date < dateToCheck2.AddDays(7)))
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                    {
                        controller = "Controller",
                        action = "Action"
                    })
                );
        }
    }
}

您可以像这样将其应用于控制器的操作:

    [MyCustomAttribute]
    public IActionResult Action()
    {
        return View();
    }