【问题标题】:How to use fallback routing in asp.net core?如何在 asp.net core 中使用后备路由?
【发布时间】: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


【解决方案1】:

使用控制器和attribute routing 真的很简单。 首先,使用app.MapControllers();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}");
    }
}

路由表将首先检查是否存在完全匹配(例如/about/support),如果没有,if 将尝试查找具有匹配参数的路由(例如/Métoule 将匹配@987654328 @路线)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2020-06-27
    相关资源
    最近更新 更多