从路由配置到属性路由

时间:2017-01-23 10:13:22

标签: asp.net-web-api attributerouting

我在ASP.NET Web API 2项目中配置了以下路由:

        config.Routes.MapHttpRoute(
            name: "1MandatoryStringParameter",
            routeTemplate: "api/{controller}/{data}",
            defaults: null,
            constraints: new { data = @".+?" }

它与以下控制器方法一起使用(请注意ArrayInput属性):

[ArrayInput("data",Separator = ',')]
public async Task<IHttpActionResult> Get(int[] data)
{
...
}

我想改用属性路由。

我尝试使用以下属性替换对 MapHttpRoute 的调用:

[HttpGet]
[Route("api/ActionsForItemTypesList/{data:regex(.+?)}", Name = "1MandatoryStringParameter")]

开箱即用它不起作用。我无法通过以下网址访问我的方法:

api/ActionsForItemTypesList/1,2

如果找不到404方法。

这适用于路由配置。

任何帮助表示感谢。

编辑:修复了客户端网址。

编辑2 :这是一个ApiExplorer问题(Swashbuckle杠杆ApiExplorer)

如果我修改Route属性并删除参数(即{data}),则ApiDescription可用。

1 个答案:

答案 0 :(得分:0)

确保您已启用属性路由:

config.MapHttpAttributeRoutes();

同样在Route属性中,您已指定data参数必须是路径的一部分而不是查询字符串。因此,请确保从客户端正确调用操作:

api/ActionsForItemTypesList/1,2

另请注意,您在路线属性中指明的前缀是api/ActionsForItemTypesList而不是api/Controller,就像您尝试调用它一样。

相关问题