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
中使用传统路由?
答案 0 :(得分:6)
你需要这样命名你的路线:
[Route("api/companies/{companyId:Guid}", Name="MyRouteName")]
然后使用
Url.Link("MyRouteName", new { companyId = company.Id })