我正在使用帶有控制器的 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();
uj5u.com熱心網友回復:
使用控制器和屬性路由真的很簡單。app.MapControllers();首先,使用(before )添加控制器支持app.Run()。
然后,使用適當的路由宣告您的控制器。為簡單起見,我添加了一個只回傳簡單字串的字串。
public class MyController : ControllerBase
{
[HttpGet("/about")]
public IActionResult About()
{
return Ok("About");
}
[HttpGet("/support")]
public IActionResult Support()
{
return Ok("Support");
}
[HttpGet("/support/new-request")]
public IActionResult SupportNewRequest()
{
return Ok("New request support");
}
[HttpGet("/{username}")]
public IActionResult About([FromRoute] string username)
{
return Ok($"Hello, {username}");
}
}
路由表將首先檢查是否存在完全匹配(例如 for/about或/support),如果沒有,if 將嘗試查找具有匹配引數的路由(例如/Métoule將匹配該/{username}路由)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/414075.html
標籤:
上一篇:如何將NamedHttpClient注入TypedHttpClient
下一篇:Map()fork在EndpointRoutingMiddleware和EndpointMiddleware之間呼叫管道是什么意思?
