我想支持像 mydomain.com/userName 这样的 URL,其中 userName 是他们尝试访问的人员页面的用户名。在 .cshtml 页面顶部添加
@page {"userName"}
后,我收到 404 错误。如果删除 {"userName"}
,我将不再收到 404,但会在没有页面参数的情况下调用标准 OnGetAsync()
。这是所有代码:
在cshtml.cs中
public async Task<IActionResult> OnGetAsync(string userName)
{
var performer = await DbContext.Users.FirstOrDefaultAsync(u => u.UserName == userName);
return Page();
}
在 .cshtml 的顶部
@page "{userName}"
并在Program.cs中
app.Use(async (context, next) =>
{
var path = context.Request.Path.Value;
// Check if the requested path is not an existing route and is not the root path
if (!string.IsNullOrEmpty(path) && path != "/" && !path.Contains("."))
{
// Check if the requested path matches an existing endpoint
var endpointFeature = context.Features.Get<IEndpointFeature>();
if (endpointFeature?.Endpoint == null)
{
// Extract username and check if it exists in the database
using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var userName = path.TrimStart('/');
var performer = await dbContext.Users.FirstOrDefaultAsync(u => u.UserName == userName);
if (performer != null)
{
// Rewrite the path to point to the Performers/Home page and keep the userName as a route value
context.Request.Path = "/Users/Home";
context.Request.RouteValues["userName"] = userName;
await next();
return; // Avoid calling next twice
}
}
}
await next();
});
事实证明整个问题就是这一行:
context.Request.RouteValues["userName"] = userName;
我必须将其更改为
context.Items["userName"] = userName;