ASP.NET MVC Razor,使用 url /profile/{username} 生成配置文件

ASP.NET MVC Razor, generate profile using url /profile/{username}

我正在尝试根据 url 创建用户配置文件。 我知道如何从 url 获取参数,例如 www.domain.com/profile?id=username 但我想保持它对 SEO 友好,而不是从 url 格式中获取价值: www.domain.com/profile/用户名

我正在使用 Visual Studio 2017 年的 MVC Razor 并放弃了 MSSQL 数据库,而是使用 table.

用户实现了 MySQL

我的想法应该如何运作。 用户访问网页www.domain.com/profile/user235

服务器加载控制器并获取输入"user235"

控制器将输入发送到 .cshtml 页面,.cshtml 页面执行 查询 MySQL 数据库获取用户数据数组并用数据填充页面。

我的想法对吗?我应该如何处理这个问题有什么建议或建议吗?

编辑:找到解决方案:https://docs.microsoft.com/en-us/aspnet/web-pages/overview/routing/creating-readable-urls-in-aspnet-web-pages-sites

@UrlData[0].ToString()

这将在 razor 页面中的 / 之后获得任何值 例子: profile.cshtml 有字符串 username = @UrlData[0].ToString()

www.domain.com/profile/约翰

@UrlData[0].ToString() = "John"

如果你想要 www.domain.com/profile/John/blog43

字符串用户名=@UrlData[0].ToString() 字符串 blogid = @UrlData[1].ToString()

利用这些信息,您可以查询数据库以获取信息... 确保为任何类型的 sql 注入验证用户名和博客输入。

我觉得应该对你有帮助,请看看https://blog.mariusschulz.com/2016/07/21/generating-route-urls-in-asp-net-core-mvc

您可以定义一个路由定义以获得 seo 友好url这样

这是使用属性路由的方法

public class ProfileController : Controller
{
    [Route("Profile/{userId}")]
    public ActionResult Index(string userId)
    {
        return Content("Proile for " + userId);
    }
}

因此,当您访问 /yourSite/profile/scott 时,Profile 控制器的 Index 操作将被执行,并且来自 url (scott) 的用户名值将在操作方法的 userId 参数中可用。这里我只是返回一个字符串 "Profile for scott"。但是您可以更新它以查询您的数据库以获取相应的记录并将该信息传递给使用视图模型的视图。

如果您使用的是 Razor 页面,您将创建一个配置文件页面及其模型并指定路由

@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 中传递的用户名打印一个字符串。但是您可以更改它以从您的数据库中获取数据 table.