如何在 ASP.NET 核心中默认添加一个 URL 参数
How to add a URL parameter by default in ASP.NET Core
我正在做一个项目,我需要从应用程序启动时的 URL 字符串访问 windows 用户名。我试图让它在应用程序启动后立即将“?windowsusername=name”添加到 URL。如果我将它重定向到另一个操作,它会弄乱我的路由。有没有办法在启动时添加这个?我从 Startup.cs 文件传入它,我知道它正在传入,因为我可以使用 Razor 引用它。但是,它没有被添加到 URL 字符串中。这是我在 Startup.cs 文件中尝试过的内容:
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{windowsUsername}",
defaults: new { controller = "Home", action = "Index", windowsUsername = "name" });
});
您应该将路线更改为以下路线:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
}
然后在操作中您可以从 id
.
访问用户名
public ActionResult YourActionNameGoesHere(string id)
{
}
如果您点击 ControllerName/YourActionName/name
,则该 ID 的值为 name
。
我正在做一个项目,我需要从应用程序启动时的 URL 字符串访问 windows 用户名。我试图让它在应用程序启动后立即将“?windowsusername=name”添加到 URL。如果我将它重定向到另一个操作,它会弄乱我的路由。有没有办法在启动时添加这个?我从 Startup.cs 文件传入它,我知道它正在传入,因为我可以使用 Razor 引用它。但是,它没有被添加到 URL 字符串中。这是我在 Startup.cs 文件中尝试过的内容:
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{windowsUsername}",
defaults: new { controller = "Home", action = "Index", windowsUsername = "name" });
});
您应该将路线更改为以下路线:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
}
然后在操作中您可以从 id
.
public ActionResult YourActionNameGoesHere(string id)
{
}
如果您点击 ControllerName/YourActionName/name
,则该 ID 的值为 name
。