【问题标题】:How to append current DateTime as a string to a URL in RouteConfig.cs如何将当前日期时间作为字符串附加到 RouteConfig.cs 中的 URL
【发布时间】:2021-05-03 20:24:54
【问题描述】:

所以我的RouteConfig.cs中有以下路线

routes.MapRoute(
    name: "Student",
    url: "student",
    defaults: new { controller = "Home", action = "Student", id = UrlParameter.Optional }
);

基于这条路线,我的Home控制器中有以下方法:

public ActionResult Student()
{
    return View();
}

当调用http://localhost:54326/student 时,这条简单的路线会将我带到学生视图。到目前为止一切顺利。

当我自动调用上述路由时,如何实现这条路由:http://localhost:54326/student/01-28-2021

基本上,我想在调用原始路由时在其末尾附加一个字符串。

我可以在RouteConfig 中指定什么来实现这一点吗?

【问题讨论】:

  • 为什么不简单地使用日期作为参数?你去了多少次约会?
  • 我不想输入日期字符串。我希望在调用原始 url 时将当前日期作为字符串自动附加到 url。我尝试了内部重定向,但它不起作用。
  • 为什么不返回重定向?
  • @CaiusJard 我确实尝试过,但如果我这样做,我会得到这样的 URL:http://localhost:54326/Home/Student?date=01-30-2021。我正在寻找这样的 URL:http://localhost:54326/student/01-28-2021
  • 一个完全有效的问题,但我建议使用日期格式 2021-01-28 有两个原因 1) 它是一种在世界任何地方都可以识别的格式 2) 添加到一个列表(例如,浏览器历史记录)。

标签: c# asp.net-mvc asp.net-mvc-routing


【解决方案1】:

以下路由Student 将允许在调用时在http://localhost:54326/student 的末尾附加一个字符串。

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

// It is important that you add this route before the `Default` one.
// Routes are processed in the order they are listed, 
// and we need the new route to take precedence over the default.

routes.MapRoute(
    name: "Student",
    url: "Student/{date}",
    defaults: new { controller = "Home", action = "Student", date = UrlParameter.Optional}
    );

Student 动作声明:

public ActionResult Student(string date)
{
    //string dateFormat = "MM-dd-yyyy";
    string dateFormat = "dd-MM-yyyy";

    if (string.IsNullOrEmpty(date))
    {            
        return RedirectToAction("Student", new { date = DateTime.Now.ToString(dateFormat) });
    }
    else if (!DateTime.TryParseExact(date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
    {
        return RedirectToAction("ReportErrorFormat");
    }
    return View((object)date);
}

【讨论】:

  • 非常感谢您的回答,但不幸的是它没有奏效。当前日期仍未附加到 URL。
  • @Rahul Sharma:我已将Student 操作方法更改为调用RedirectToActionPermanent()。现在如果输入http://localhost:54326/student,它将返回http://localhost:54326/student/01-30-2021 URL。
  • 如何将 URL 中的日期格式从 http://localhost:54326/student/01-30-2021 更改为 http://localhost:54326/student/30-01-2021
  • @Rahul Sharma:在Student() 操作方法中进行了一些修复以支持dd-MM-yyyy 日期格式。根据所需的日期格式选择正确的dateFormat 模式。另一种方法是更改​​所有日期时间函数以使用服务器上的当前区域设置。
  • @Rahul Sharma:处理DateTime 的一些有用技巧,您可以在此处阅读:https://stackoverflow.com/q/4331189/6630084
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
相关资源
最近更新 更多