Web Api 2发布-UrlHelper.Link不得返回null [英] Web Api 2 Post - UrlHelper.Link must not return null
问题描述
我有一个基本的Web API 2设置和一些基本的路由.
I have a basic web API 2 setup with some basic routing.
以下是默认路线和插入路线.当我致电该职位时,该记录已在数据库中完美创建,但是"CreatedAtRoute"调用返回500错误,指出:
Below is the default route and post for inserts. When I call the post the record is created perfectly in the database but the "CreatedAtRoute" call returns a 500 error stating:
ExceptionMessage:"UrlHelper.Link不能返回null. ExceptionType:"System.InvalidOperationException"
ExceptionMessage: "UrlHelper.Link must not return null." ExceptionType: "System.InvalidOperationException"
为什么我会收到此错误?
Why would I receive this error?
[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);
}
推荐答案
由于您正在使用属性路由.因此,您必须命名路由. [Route("api/books/{id}",Name ="GetBookById")]
Since you are using attribute routing.. you have to name your route.. i.e. [Route("api/books/{id}", Name="GetBookById")]
,并在url.link()调用中使用路由名称
and the use the route name on your url.link() call
see details here.. http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names
这篇关于Web Api 2发布-UrlHelper.Link不得返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!