我使用的WebAPI的OData。 要求是更新实体的导航属性。
public class Question
{
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public string QuestionBody { get; set; }
public List<Response> Responses { get; set; } //navigation property
}
public class Response
{
public string ResponseId { get; set; }
public int QuestionId { get; set; } //fk
public string ResponseBody { get; set; }
}
现在,如果我使用下面的链接来获取它工作在ODATA的WebAPI的答复
GET - /的OData /问题(1)/响应----成功合作。 在控制器我添加了一个动作来处理此请求为:
public IQueryable<Response> GetResponses([FromODataUri] Guid key)
{
//
}
POST - /的OData /问题(1)/响应---- 这是行不通的 ; 错误消息:该服务不支持的格式“〜/ EntitySet的/键/导航”的OData请求
我在控制器中添加的方法是:
public List<Responses> CreateResponses([FromODataUri] Guid key, List<Response> responses)
{
//
}
我如何支持增加/中的OData的WebAPI更新导航性能
你需要一个自定义路由惯例来处理POST的导航性能。 下面的代码,
// routing convention to handle POST requests to navigation properties.
public class CreateNavigationPropertyRoutingConvention : EntitySetRoutingConvention
{
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (odataPath.PathTemplate == "~/entityset/key/navigation" && controllerContext.Request.Method == HttpMethod.Post)
{
IEdmNavigationProperty navigationProperty = (odataPath.Segments[2] as NavigationPathSegment).NavigationProperty;
controllerContext.RouteData.Values["key"] = (odataPath.Segments[1] as KeyValuePathSegment).Value; // set the key for model binding.
return "PostTo" + navigationProperty.Name;
}
return null;
}
}
注册路由惯例,
var routingConventions = ODataRoutingConventions.CreateDefault();
routingConventions.Insert(0, new CreateNavigationPropertyRoutingConvention());
server.Configuration.Routes.MapODataRoute("odata", "", GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
完整的范例在这里 。