如何将当前日期时间作为字符串附加到 RouteConfig.cs 中的 URL
How to append current DateTime as a string to a URL in RouteConfig.cs
所以我的 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
中指定的,我可以通过它来实现这个目标吗?
以下路由 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);
}
所以我的 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
中指定的,我可以通过它来实现这个目标吗?
以下路由 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);
}