Web Api 2 Post - UrlHelper.Link不得返回null

Aar*_*ind 24 asp.net-web-api2

我有一个基本的Web API 2设置与一些基本的路由.

以下是插入的默认路径和帖子.当我调用帖子时,记录在数据库中完美创建,但"CreatedAtRoute"调用返回500错误,说明:

ExceptionMessage:"UrlHelper.Link不能返回null." ExceptionType:"System.InvalidOperationException"

为什么我会收到此错误?

[RoutePrefix("api/casenotes")]
    public class CasenoteController : ApiController...



// POST api/Casenote
[Route("")]
[ResponseType(typeof(client_admission_casenote))]
    public async Task<IHttpActionResult> Postclient_admission_casenote   (client_admission_casenote client_admission_casenote)
{

  Request.GetRequestContext().IncludeErrorDetail = true;

  if (!ModelState.IsValid)
  {
      return BadRequest(ModelState);
  }

  db.client_admission_casenote.Add(client_admission_casenote);
  await db.SaveChangesAsync();

  return CreatedAtRoute("DefaultApi", new { id = client_admission_casenote.casenote_id }, client_admission_casenote);
    }
Run Code Online (Sandbox Code Playgroud)

小智 38

由于您正在使用属性路由..您必须为您的路线命名..即[Route("api/books/{id}",Name ="GetBookById")]

并在url.link()调用中使用路由名称

在这里查看详细信息.. http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names

  • 啊,那是因为我把默认的“id”值改成了“casenoteId”。我不得不更改为: CreatedAtRoute("GetSingleCasenote", new { casenoteId = client_admission_casenote.casenote_id }, client_admission_casenote); 非常感谢罗内尔!!! (2认同)