如何在ASP.NET核心中获取URL参数路由

时间:2017-01-30 01:32:03

标签: asp.net-core

我的ASP.NET核心的默认路由默认为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'.

我对attritube路由没有经验,也不明白为什么上面的控制器方法不能给我相同的结果。

1 个答案:

答案 0 :(得分:1)

默认路由模板为{controller=Home}/{action=Index}/{id?} 所以你可以按照控制器动作中的模板进行操作

my-controller将是controller类中的继承类,IActionResult与您的操作方法匹配,如果您在put中指定了属性以路由{Id} ,在你的方法参数中也应该具体{Id},在路由中,你还需要具体的http动词动作(GET,POST,PUT等)

在您的情况下

将是

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