我有一个Web API控制器向Angular SPA提供数据,我决定重命名,使用VS 2015的重命名功能来更新我的所有引用。因此,我不能再发布它了(GET仍然有效),我在客户端上不断收到以下错误:
"A route named 'api/Trainees' could not be found in the route collection.
Parameter name: name"
此控制器以前使用默认路由工作正常 - RouteConfig.cs
中没有任何内容,也没有属性路由,这使得它更加陌生。我假设ASP.NET仅根据控制器和方法名称计算出默认路由,或者它是否在任何地方缓存路由信息?
我的控制器看起来像这样:
public class TraineesController : ApiController
{
private UserRepository repo = new UserRepository();
// GET: api/Trainees
public IEnumerable<Trainee> Get()
{
return this.repo.GetUsers();
}
// GET: api/Trainees/5
public Trainee Get(string email)
{
if (!string.IsNullOrEmpty(email))
{
return this.repo.GetUser(email);
}
throw new ArgumentNullException("email");
}
// POST: api/Trainees
public IHttpActionResult Post([FromBody]Trainee value)
{
try
{
this.repo.AddUser(value);
return CreatedAtRoute("api/Trainees", value.Email, value);
}
catch (ArgumentOutOfRangeException)
{
return Conflict();
}
}
// PUT: api/Trainees/5
public IHttpActionResult Put([FromBody]Trainee value)
{
try
{
this.repo.UpdateUser(value);
return StatusCode(HttpStatusCode.NoContent);
}
catch (ArgumentOutOfRangeException)
{
return NotFound();
}
}
// DELETE: api/Trainees/5
public IHttpActionResult Delete(string email)
{
try
{
this.repo.RemoveUser(email);
return StatusCode(HttpStatusCode.NoContent);
}
catch (ArgumentOutOfRangeException)
{
return NotFound();
}
}
}
这是失败的请求(由Angular $资源生成):
Request: POST /api/Trainees HTTP/1.1
Content-Type: application/json;charset=utf-8
Accept: application/json, text/plain, */*
Referer: http://localhost:11423/
Accept-Language: en-GB
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: localhost:11423
Content-Length: 64
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
体:
{"Email":"tony@starkindustries.com","DisplayName":"Tony Stark"}
答案 0 :(得分:2)
有点晚了,但这是因为您尝试将route template
作为CreatedAtRoute
return CreatedAtRoute("api/Trainees", value.Email, value);
您需要传递路线名称。您可以使用 RouteAttribute
[Route("api/Trainees", Name="TraineesRoute")]`