gpt4 book ai didi

c# - Endpoints.MapControllerRoute 模式含义

转载 作者:行者123 更新时间:2023-12-04 07:28:06 25 4
gpt4 key购买 nike

在这样的模式中分配 Controller 名称和 Action 名称有什么用

endpoints.MapControllerRoute(
name:"default",
pattern: "{controller=home}/{action=index}/{id?}"
);

最佳答案

像这样的模式

"{controller=home}/{action=index}/{id?}"

告诉 ASP.NET Core,如果 URL 以路径 /MyController/MyAction/MyId123 结尾,它应该将请求分派(dispatch)给 Controller 内的方法 MyAction 我的 Controller 。该方法可能如下所示:

public class MyController {
public IActionResult MyAction(string id) {
// ...
}
}

现在,通过添加 =home=index,您可以给它一个默认值,并有效匹配所有未映射到现有 Controller 和操作的请求到 HomeController:Index 方法。

来自docs :

The route template "{controller=Home}/{action=Index}/{id?}":

  • Matches a URL path like /Products/Details/5

  • Extracts the route values { controller = Products, action = Details, id = 5 } by tokenizing the path. The extraction of route valuesresults in a match if the app has a controller namedProductsController and a Details action:

    public class ProductsController : Controller {
    public IActionResult Details(int id)
    {
    return ControllerContext.MyDisplayRouteInfo(id);
    }
    }
  • {controller=Home} defines Home as the default controller.

  • {action=Index} defines Index as the default action.

  • The ? character in {id?} defines id as optional.

关于c# - Endpoints.MapControllerRoute 模式含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68113418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com