如何在ASP.NET Core中实现URL参数路由

4

我的ASP.NET Core的默认路由与VS2015默认设置相同:

routes.MapRoute(
   name: "default",
   template: "{controller=Home}/{action=Index}/{id?}");

当我请求URL /my-controller/my-special-view时,它确实调用了我在my-control中定义的方法,该方法如下所示,其中id参数等于my-special-value。
public IActionResult my-controller(string id) {...

我正在尝试使用属性路由实现相同的功能。我定义属性如下:

[Route("my-controller/{id}")]
public IActionResult my-controller(string id) {...

我收到以下错误信息:

InvalidOperationException: The constraint entry 'attributeOfInterest' - 'string' on the route 'CacheTagHelper/{attributeOfInterest:string}' could not be resolved by the constraint resolver of type 'DefaultInlineConstraintResolver'.

我没有经验使用属性路由,不明白为什么上述两个控制器方法不能给我相同的结果。

1个回答

4

默认的路由模板是{controller=Home}/{action=Index}/{id?},因此您可以在控制器操作中遵循该模板

my-controller将是您从controller类继承的类,并且IActionResult与您的操作方法匹配。如果您在路由中指定了属性{Id},则在方法参数中也应指定{Id}。在路由中,您还需要指定HTTP动词操作(GET、POST、PUT等)

在您的情况下,应该是:

public class my-controller : Controller
{
   [HttpGet("{id}")]
   public IActionResult my-special-view(String id) { ... }
}

你另一个关于“FromRoute”的答案怎么样?具体而言,我想要使用路由属性,这样我就可以在控制器中创建模板,而不是在启动类中创建。 - Peter Kellner
使用 [HttpGet("{id}")] 实际上给我带来了问题。对我来说,仅使用 [HttpGet] 就可以正常工作。你可能想在这里阅读:https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing#setting-up-routing-middleware - Blaze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接