gpt4 book ai didi

c# - 如何编写包含用户名的路由

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:00 24 4
gpt4 key购买 nike

我正在建立一个 asp.net mvc 网站,用户登录后他可以访问他的个人资料部分页面,目前这些页面的 URL 是这样的 www.example.com/profile ,我想要的是使 URL 像那样www.example.com/用户名

如何编写这条路由,当用户登录时,它只在个人资料页面中起作用?

更新:

根据下面的回答,我是这样写的:

routes.MapRoute(
"AccountSettins",
"AccountSettings",
new { controller = "AccountSettings", action = "Index" }
);

routes.MapRoute(
"myRouteName",
"{username}",
new { controller = "Profile", action = "Index" }
);


routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

和 Controller :

[Authorize]
public class ProfileController : BaseController
{
//
// GET: /Profile/

public ActionResult Index(string username= "")
{ ...

但是现在在用户登录并且他的用户名为“xyz”之后他可以去 www.example.com/xyz 这将导致个人资料页面,但是如果他也写了 url www.example.com/abc 他通常会转到相同的个人资料页面,这从用户的角度来看很奇怪,如何解决这个问题?

最佳答案

在您的 Global.asax 中...

routes.MapRouteWithName(
"routeUserProfile",
"{username}",
new { controller = "User", action = "Profile", username = "" });

在你的用户 Controller 中....

public ActionResult Profile(string username) {
//conditional logic to check if username is user
// render user profile with special user-only stuff
//else
// render only generic stuff about user
}

关于c# - 如何编写包含用户名的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com