Url.Link():使用属性路由时找不到路由

时间:2014-11-07 09:12:56

标签: asp.net-web-api asp.net-mvc-routing asp.net-web-api2

Url.Link(...)上抛出以下异常:

An exception of type 'System.ArgumentException' occurred in System.Web.dll but was not handled in user code

Additional information: A route named 'api/companies/{companyId:Guid}' could not be found in the route collection.

这是控制器方法:

[Route("api/companies/")]
[HttpPost]
public IHttpActionResult Create()
{
    Company company = new Company("Test!");

    CompanyRepository.Add(company);

    return Created(new Uri(Url.Link("api/companies/{companyId:Guid}", new { companyId = company.Id })), company);
}

此处使用属性路由定义路径:

[Route("api/companies/{companyId:Guid}")]
[HttpGet]
public IHttpActionResult Get(Guid companyId)
{
    return Ok(CompanyRepository.Find(companyId));
}

为什么无法找到路线?我是否需要在RouteConfig中使用传统路由?

1 个答案:

答案 0 :(得分:6)

你需要这样命名你的路线:

[Route("api/companies/{companyId:Guid}", Name="MyRouteName")]

然后使用

Url.Link("MyRouteName", new { companyId = company.Id })