更新时间:2022-12-06 22:24:14
您可以定义路由定义以获取类似seo的网址
You can define a route definition to get seo friendly urls like that
这是使用属性路由的方法
Here is how you do it with attribute routing
public class ProfileController : Controller
{
[Route("Profile/{userId}")]
public ActionResult Index(string userId)
{
return Content("Proile for " + userId);
}
}
因此,当用户访问/yourSite/profile/scott
时,将执行Profile控制器的Index操作,并且该操作的userId参数中将提供来自url(scott)的用户名值方法.在这里,我只是返回一个字符串"scott的配置文件".但是您可以对其进行查询以查询数据库以获得相应的记录,然后使用视图模型将该信息传递给视图.
So when you user access /yourSite/profile/scott
the Index action of Profile controller will be executed and the username value from the url (scott) will be available in the userId parameter of the action method. Here i am simply returning a string "Profile for scott". But you can udpate it to query your database to get the corresponding record and pass that information to a view using a view model.
如果使用的是Razor页面,则将创建一个Profile页面及其模型并指定路线
If you are using Razor pages, you will create a Profile page and it's model and specify the route
@page "{id:int}"
@model ProfileModel
@{
ViewData["Title"] = "Profile";
}
<h3>@Model.Message</h3>
并在您的 Profile.cshtml.cs
public class ProfileModel : PageModel
{
public string Message { get; set; }
public void OnGet(string id)
{
Message = "Profile of "+ id;
}
}
就像我上面提到的,我只是打印一个带有URL中传递的用户名的字符串.但是您可以更改它,以从db表中获取数据.
Like i mentioned above, i am just printing a string with the passed username from the url. But you can change it to get your data from your db table.