【发布时间】:2022-01-17 11:25:50
【问题描述】:
我正在使用带有控制器的 asp.net web-api。 我想做一个用户部分,可以在其中请求站点地址,并在其后使用用户名,例如 example.com/username。其他已注册的路由,如 about、support 等应该有更高的优先级,所以如果你输入 example.com/about,about 页面应该首先出现,如果不存在这样的 about 页面,它会检查是否有该名称的用户存在。我只找到了一种 SPA 回退路由的方法,但是我不使用 SPA。让它在中间件中手动工作,但是更改它非常复杂。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
string[] internalRoutes = new string[] { "", "about", "support", "support/new-request", "login", "register" };
string[] userNames = new string[] { "username1", "username2", "username3" };
app.Use(async (context, next) =>
{
string path = context.Request.Path.ToString();
path = path.Remove(0, 1);
path = path.EndsWith("/") ? path[0..^1] : path;
foreach (string route in internalRoutes)
{
if (route == path)
{
await context.Response.WriteAsync($"Requested internal page '{path}'.");
return;
}
}
foreach (string userName in userNames)
{
if (userName == path)
{
await context.Response.WriteAsync($"Requested user profile '{path}'.");
return;
}
}
await context.Response.WriteAsync($"Requested unknown page '{path}'.");
return;
await next(context);
});
app.Run();
【问题讨论】:
-
您能告诉我们您是如何注册您的路线的吗?
-
@Métoule 我已经用我当前使用的代码(最小的 api)编辑了我的问题,但是我想用控制器来做,让它更有条理。
标签: asp.net-core asp.net-web-api asp.net-mvc-routing .net-6.0