gpt4 book ai didi

asp.net-web-api - 网址链接() : Route cannot be found when using attribute routing

转载 作者:行者123 更新时间:2023-12-02 08:31:00 25 4
gpt4 key购买 nike

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.

Controller 方法如下:

[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中使用常规路由吗?

最佳答案

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

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

然后使用

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

关于asp.net-web-api - 网址链接() : Route cannot be found when using attribute routing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26797743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com